这是我的代码。我省略了向量的代码,因为它不重要。
什么是解决这个问题的最佳方法?
#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.
什么是解决这个问题的最佳方法?
std::max_element
的函数,这个函数名称有些欺骗性。std::max
并不是你所认为的那样,如果你仔细阅读手册,就可以轻松发现这一点。 - Igor Tandetnik