Consider a class A having a member x and a std::vector< A >. Now its a common task to search for the maximal x among all elements inside the vector. Clearly I can only use std::max_element if there is an iterator on the x's. But I must write one by my own, or I just make a simple for loop.
maxSoFar = -std::numeric_limits< double >::max();
for( std::vector< A >::const_iterator cit = as.begin(); cit != as.end(); ++cit )
{
if( cit->x > maxSoFar )
maxSoFar = cit->x;
}
but it's so tedious, and I am so lazy.. Is there a better option?
You can use the max_element() function to find the position of the maximum element.
To find a largest or maximum element of a vector, we can use *max_element() function which is defined in <algorithm> header. It accepts a range of iterators from which we have to find the maximum / largest element and returns the iterator pointing the maximum element between the given range.
Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL. Syntax: *max_element (first_index, last_index);
You can pass a comparator to max_element. And if your compiler supports lambdas(it probably does), this is easy:
std::max_element(as.begin(), as.end(),
[](A a, A b){ return a.x < b.x; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With