pot*_*eno 5 c++ algorithm iterator vector 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");
}
Run Code Online (Sandbox Code Playgroud)
据我了解, std::max 返回一个迭代器,但我真的不知道如何处理该迭代器。我看过这个例子
*max(scores.begin(), scores.end())
Run Code Online (Sandbox Code Playgroud)
让它返回索引而不是迭代器,但它得到错误
Expression: vector iterator not dereferencable
Run Code Online (Sandbox Code Playgroud)
我尝试使用迭代器,然后使用 std::distance
vector<int>::iterator high = std::max(scores.begin(), scores.end());
cout << "High score: " << scores[std::distance(scores.begin(), high)] << endl;
Run Code Online (Sandbox Code Playgroud)
但我得到了错误
Expression: vector subscript is out of range.
Run Code Online (Sandbox Code Playgroud)
解决这个问题的最佳方法是什么?
std::max_element
标头中声明的标准算法<algorithm>
可以满足您的需要。
例如
#include <algorithm>
//...
cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;
Run Code Online (Sandbox Code Playgroud)
假设向量不为空。
至于这个电话
std::max(scores.begin(), scores.end())
Run Code Online (Sandbox Code Playgroud)
然后它返回这两个迭代器中的最大迭代器。并且 对应的迭代器end()
总是大于或等于(如果向量为空)对应的迭代器begin()
。