【发布时间】:2015-08-22 17:58:18
【问题描述】:
这是我的代码。我省略了向量的代码,因为它并不重要。
#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并不像您认为的那样做,正如您通过阅读精美的手册很容易发现的那样。
标签: c++ algorithm vector iterator max