In C ++ 11, how can I call std :: max for a vector?

I have a vector<data> (where data is my own type of pet) and I want to find its maximum value.

The standard function std::max in C ++ 11 works with a collection of objects, but it wants the list of initializers to be selected as the first argument, and not a set, for example vector :

 vector<data> vd; std::max(vd); // Compilation error std::max({vd[0], vd[1], vd[2]}); // Works, but not ok since I don't vd.size() at compile time 

How can i solve this?

+7
c ++ c ++ 11 std initializer-list
source share
2 answers

The std::max overloads are only for small sets known at compile time. You need std::max_element (this is even before 11). This returns the iterator to the maximum element of the collection (or any range of iterators):

 auto max_iter = std::max_element(vd.begin(), vd.end()); // use *max_iter as maximum value (if vd wasn't empty, of course) 
+18
source share

Probably more flexible with lambda

 vector<data> vd; auto it = max_element(vd.cbegin(), vd.cend(), [](const data& left, const data& right) { return (left < right); }); 

You just need to implement the comparison operator for your "data" type using data::operator < ()

+1
source share

All Articles