这是我的代码。我省略了 vector 的代码,因为它并不重要。
#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.
解决这个问题的最佳方法是什么?
最佳答案
在 header std::max_element
中声明了一种名为<algorithm>
的标准算法,该算法可以满足您的需求。
例如
#include <algorithm>
//...
cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;
假定 vector 不为空。
至于这个电话
std::max(scores.begin(), scores.end())
然后返回这两个迭代器中的最大迭代器。并且对应于
end()
的迭代器始终大于或等于(如果 vector 为空)对应于begin()
的迭代器。