我如何找到一个向量的最大元素(c++)

How do I find the max element in a vector (C++)?

本文关键字:元素 c++ 向量 一个 何找      更新时间:2023-10-16

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

#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. 
解决这个问题的最好方法是什么?

在标题<algorithm>中声明了一个名为std::max_element的标准算法,它可以满足您的需求。

例如

#include <algorithm>
//...
cout << "High score: " << *std::max_element( scores.begin(), scores.end() ) << endl;

假设vector不为空。

对于这个呼叫

std::max(scores.begin(), scores.end())

则返回这两个迭代器中最大的迭代器。并且end()对应的迭代器总是大于或等于begin()对应的迭代器(如果向量为空)。

最好的方法是使用max_element:

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];

你必须只使用第一种方式!