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.
source share