Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding max_element of a vector where a member is used to decide if its the maximum

Tags:

c++

max

stl

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?

like image 994
math Avatar asked Oct 22 '10 07:10

math


People also ask

How do you find the maximum position of a vector element?

You can use the max_element() function to find the position of the maximum element.

How do you find the max of a vector in C++?

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.

How do you find Max in STL?

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);


1 Answers

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; });
like image 132
Benjamin Lindley Avatar answered Oct 04 '22 22:10

Benjamin Lindley