这是我的代码。我省略了 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.
解决这个问题的最佳方法是什么?
最佳答案
有一个名为std::max_element
的标准算法在 header 中声明 <algorithm>
那就是你需要的。
例如
#include <algorithm>
//...
cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;
假设 vector 不为空。
至于这个电话
std::max(scores.begin(), scores.end())
然后它返回这两个迭代器中的最大迭代器。以及end()
对应的迭代器总是大于或等于(如果 vector 为空)对应于 begin()
的迭代器.
关于c++ - 如何找到 vector 中的最大元素 (C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159151/