【问题标题】:How can I find the maximum value in this queue?我怎样才能找到这个队列中的最大值?
【发布时间】:2017-12-16 04:23:42
【问题描述】:

我想在这个队列中找到最大值,我该如何解决?

queue<pair<int , int> > q;
 for(int i = 1; i <= n; i++){ 
  int p; 
  cin >> p; 
  q.push(make_pair(p, i)); 
 }

【问题讨论】:

  • 到目前为止你做了什么?
  • queue&lt;pair&lt;int , int&gt; &gt; q; for(int i = 1; i &lt;= n; i++){ int p; cin &gt;&gt; p; q.push(make_pair(p, i)); } 想在该代码中找到最大值...
  • 将 var max 定义为等于第一个元素。从队列中逐一弹出或出列所有元素,并且每次与您定义的 max 变量进行比较,如果当前元素大于最大值,则使 max = current 最后您拥有最大元素

标签: c++11 queue


【解决方案1】:

我希望我正确理解了您的问题,如果没有,请发表评论,请检查此代码,我希望它能满足您的任何需求。

queue<pair<int , int> > q; 
int max=-1;//you can use INT_MIN in case you're accepting negative numbers too 

for(int i = 1; i <= n; i++)
{ 
int p;
 cin >> p; 
//if you need to be based ONLY on user input 
if(p > max) max = p;
//if you need to be based on BOTH user input and current i
//if(p+i > max) max = p+I;
//if you need to be based on ONLY current i
//if(i > max) max = i;
q.push(make_pair(p, i)); 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2014-07-05
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多