我一直在使用 std::max_element(vec)
,但据我所知,如果两个“最大”索引相等,它会返回最小索引。
例子:
vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
std::max_element(v)
将引用 v[4]
,但出于我的项目的目的,我需要它引用 v[8]
代替。执行此操作的最佳方法是什么?
最佳答案
你可以用这个
max_element(v.rbegin(), v.rend());
引用最大值的最大索引。
例如,
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
*max_element(v.rbegin(), v.rend())=-1;
for (auto i: v) cout << i << ' ';
}
产生输出
1 2 3 4 5 3 3 2 -1
正如@BoBTFish 所指出的,上面提到的方法返回一个反向迭代器。要获得前向迭代器,您可以这样做:
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
int main()
{
vector <int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
reverse_iterator < vector <int> :: iterator > x (max_element(v.rbegin(), v.rend()));
vector <int> :: iterator it=--x.base(); // x.base() points to the element next to that pointed by x.
*it=-1;
*--it=0; // marked to verify
for (auto i: v) cout << i << ' ';
}
产生输出
1 2 3 4 5 3 3 0 -1
^
可以看出迭代器it
是一个前向迭代器。
关于c++ - 如果有两个 "greatest"索引,我如何找到 vector 中最大值的索引,默认为更大的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35681372/