如何在向量中找到max元素(C ++)?

时间:2015-08-22 17:58:18

标签: c++ vector iterator max

这是我的代码。我省略了向量的代码,因为它并不重要。

#include <string>
#include <iostream>
#include <vector>
using namespace std;


int main() {
    vector<int> scores;

    // code to make vector

    cout << "High score: " << scores[std::max(scores.begin(), scores.end())] << endl;
    system("pause");
}

我的理解是std :: max返回一个迭代器,但我真的不知道如何处理迭代器。我见过这个例子

*max(scores.begin(), scores.end())

让它返回索引而不是迭代器,但它得到错误

Expression: vector iterator not dereferencable

我尝试使用迭代器,然后使用std :: distance

vector<int>::iterator high = std::max(scores.begin(), scores.end());
cout << "High score: " << scores[std::distance(scores.begin(), high)] << endl;

但我收到了错误

Expression: vector subscript is out of range. 

解决此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

在标题UICollectionView中声明了标准的std::max_element算法,可以满足您的需求。

例如

<algorithm>

假设矢量不为空。

至于这个电话

#include <algorithm>

//...

cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;

然后它返回这两个迭代器中的最大迭代器。对应std::max(scores.begin(), scores.end()) 的迭代器总是大于或等于(如果向量为空)与end()对应的迭代器。

答案 1 :(得分:0)

最好的方法是使用max_element:

vector<int> scores;
//input
vector<int>::iterator it;
it=max_element(scores.begin(),scores.end());
cout<<*it;

如果你想要max而不关心时间复杂性 你也可以使用它(不建议这样做):

sort(scores.begin(),scores.end());
cout<<scores[scores.size()-1];

您必须只使用第一种方式!