How to find the index of the highest value in a vector, by default for a larger index, if there are two "greatest" indexes?

I used std::max_element(vec) , but from what I can say, it returns the smallest index if the two "largest" indices are equal.

Example:

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

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

+5
source share
2 answers

You can use this

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

to indicate the largest index of the largest value.

For instance,

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

outputs a conclusion

 1 2 3 4 5 3 3 2 -1 

The method mentioned above returns a reverse iterator as indicated by @BoBTFish. To get a forward iterator, you can 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 << ' '; } 

outputs a conclusion

 1 2 3 4 5 3 3 0 -1 ^ 

You can see that the iterator it is a forward iterator.

+8
source

It is very easy to make your own function:

 /* 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; } 
+4
source

Source: https://habr.com/ru/post/1244038/


All Articles