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

Pan*_*tle 6 c++ algorithm vector

我一直在使用std::max_element(vec),但据我所知,如果两个"最大"指数相等,它会返回最小的索引.

例:

vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};
Run Code Online (Sandbox Code Playgroud)

std::max_element(v)会参考v[4],但为了我的项目的目的,我需要它来引用v[8].最好的方法是什么?

anu*_*kul 9

你可以用它

max_element(v.rbegin(), v.rend());
Run Code Online (Sandbox Code Playgroud)

指最大价值的最大指数.

例如,

#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 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

产生输出

1 2 3 4 5 3 3 2 -1 
Run Code Online (Sandbox Code Playgroud)

上面提到的方法返回一个反向迭代器,正如@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 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

产生输出

1 2 3 4 5 3 3 0 -1 
              ^
Run Code Online (Sandbox Code Playgroud)

可以看出迭代器it是一个前向迭代器.


bol*_*lov 5

制作自己的函数很容易:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)