Reputation: 83
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?
Upvotes: 8
Views: 14771
Reputation: 1952
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.
Upvotes: 10
Reputation: 75698
It's 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;
}
Upvotes: 5