Search for the max_element of the vector in which the element is used to decide if it has a maximum

Consider a class A having an element x and a std :: vector A>. Now his general task is to find the maximum x among all the elements inside the vector. Clearly, I can only use std :: max_element if there is an iterator on x. But I have to write one myself, or just make a simple 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 is so tiring and I'm so lazy. Is there a better option?

+6
c ++ max stl
source share
4 answers

If you can use boost , then you can write a lambda expression for the binary predicate expected by max_element :

 struct A { A(int n): x(n) { } int x; }; using namespace std; using namespace boost::lambda; int main() { vector<A> as; as.push_back(A(7)); as.push_back(A(5)); as.push_back(A(3)); vector<A>::iterator iter = max_element(as.begin(), as.end(), bind(&A::x, _2) > bind(&A::x, _1)); int max = iter->x; } 
+6
source share

You can pass a comparator to max_element. And if your compiler supports lambdas (maybe it is), this is easy:

 std::max_element(as.begin(), as.end(), [](A a, A b){ return ax < bx; }); 
+21
source share

1) Change the first line as follows:

 maxSoFar = *(as.begin()); 

2) Implement a custom comparator and use max_element (as you wish): http://www.cplusplus.com/reference/algorithm/max_element/

+1
source share

Bring operator< to your class, call:

 maxSoFar = *(std::max_element(as.begin(), as.end())); 
0
source share

All Articles