我如何找到一个向量的最大元素(c++)
How do I find the max element in a vector (C++)?
这是我的代码。我省略了向量的代码,因为它不重要。
#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];
你必须只使用第一种方式!
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 擦除while循环中迭代的元素