C++ 如何在向量(C+;+;)中找到max元素?

C++ 如何在向量(C+;+;)中找到max元素?,c++,vector,iterator,max,C++,Vector,Iterator,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

这是我的密码。我省略了向量的代码,因为它不重要

#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");
}
让它返回一个索引而不是迭代器,但它得到了错误

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;

解决此问题的最佳方法是什么?

标题
中声明了一种名为
std::max\u element
的标准算法,可以满足您的需要

比如说

#include <algorithm>

//...

cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;

然后返回这两个迭代器中的最大迭代器。与
end()
相对应的迭代器始终大于或等于(如果向量为空)与
begin()
相对应的迭代器最好的方法是使用max\u元素:

vector<int> scores;
//input
vector<int>::iterator it;
it=max_element(scores.begin(),scores.end());
cout<<*it;
向量得分;
//输入
向量::迭代器;
it=max_元素(scores.begin(),scores.end());

您是否可以使用一个名称不正确的函数
std::max
不像你想象的那样,你可以通过阅读精美的手册很容易发现。我试过了,但我的编译器说“std没有成员‘max_元素’”@potapeno你必须包含标题,因为它已经在我的帖子中写过了。不过,我没有包含算法。。。这会让事情变得更糟sense@potapeno现在你知道了C++中的一个标准算法。
#include <algorithm>

//...

cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;
std::max(scores.begin(), scores.end())
vector<int> scores;
//input
vector<int>::iterator it;
it=max_element(scores.begin(),scores.end());
cout<<*it;
sort(scores.begin(),scores.end());
cout<<scores[scores.size()-1];