c++ - 如果有两个 "greatest"索引,我如何找到 vector 中最大值的索引,默认为更大的索引?

标签 c++ algorithm vector

我一直在使用 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/

相关文章:

c++ - 何时通过指针或shared_ptr传递

c++ - 在多个函数之间共享一个 vector ,我的程序没有按预期工作。

c++ - 不是从 .begin()ing 迭代一个 STL 容器并环绕

c++ - 为什么这个 C++ 静态转换代码会生成并且 int 不是 double

c++ - Solaris Studio 在目标文件中添加当前目录信息

c++ - 调试正则表达式不匹配

java - 在 Java 中组合 6 组 2 个元素

python - 将 2D 列表减少为其唯一元素并保持顺序的算法

c++ - 如何定义与使用 lambda 兼容的函数指针并将捕获作为回调

c# - 如何找到相关讲座?