如何在向量(C++)中找到最大元素?

5
这是我的代码。我省略了向量的代码,因为它不重要。
#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. 

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

3
你使用了一个名为std::max_element的函数,这个函数名称有些欺骗性。std::max并不是你所认为的那样,如果你仔细阅读手册,就可以轻松发现这一点。 - Igor Tandetnik
2个回答

7

有一个名为std::max_element的标准算法,声明在头文件<algorithm>中,它可以完成您需要的操作。

例如:

#include <algorithm>

//...

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

假设向量不为空。

关于此调用:

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

然后它返回这两个迭代器中的最大值。与 end() 相对应的迭代器始终大于或等于(如果向量为空)与 begin() 相对应的迭代器。


我尝试过了,但我的编译器显示“std没有'max_element'成员”。 - potapeno
@potapeno,你必须包含头文件<algorithm>,因为它已经写在我的帖子中了。 - Vlad from Moscow
没事,我没有包括算法...这样更有意义。 - potapeno
1
@potapeno 现在你又多了一个C++标准算法的知识点。 :) - Vlad from Moscow

1

最好的方法是使用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];

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接