如何找到向量中最高值的索引,如果有两个"greatest"索引,则默认为较大的索引?

How can I find the index of the highest value in a vector, defaulting to the greater index if there are two "greatest" indices?

本文关键字:索引 greatest 两个 默认 向量 何找 最高值 如果      更新时间:2023-10-16

我一直在使用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是一个前向迭代器。

制作自己的函数非常容易:

/* Finds the greatest element in the range [first, last). Uses `<=` for comparison.
*
* Returns iterator to the greatest element in the range [first, last).
* If several elements in the range are equivalent to the greatest element,
* returns the iterator to the last such element. Returns last if the range is empty.
*/
template <class It>
auto max_last(It first, It last) -> It
{
    auto max = first;
    for(; first != last; ++first) {
        if (*max <= *first) {
            max = first;
        }
    }
    return max;
}