Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have been using std::max_element(vec), but from what I can tell, it returns the smallest index if two "greatest" indices are equal.

Example:

vector<int> v = {1, 2, 3, 4, 5, 3, 3, 2, 5};

std::max_element(v) would reference v[4], but for the purposes of my project I need it to reference v[8] instead. What would be the best way to do this?

like image 489
PanicSkittle Avatar asked Feb 28 '16 10:02

PanicSkittle


People also ask

How do you find the maximum index of a vector?

To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element , respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element.

How do you find the index element of a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do you find the index of a maximum vector in Matlab?

You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable. Here, 7 is the largest number at the 4th position(index).


1 Answers

You can use this

max_element(v.rbegin(), v.rend());

to refer to the greatest index of the greatest value.

For example,

#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 << ' ';
}

produces output

1 2 3 4 5 3 3 2 -1 

The method mentioned above returns a reverse iterator, as pointed out by @BoBTFish. To get a forward iterator, you could do this:

#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 << ' ';
}

produces output

1 2 3 4 5 3 3 0 -1 
              ^

It can be seen that the iterator it is a forward iterator.

like image 81
anukul Avatar answered Oct 24 '22 07:10

anukul