Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c++11, how can I call std::max on a vector?

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

The standard std::max function in C++11 appears to work on a collection of objects, but it wants an initializer list as its first argument, not a collection like 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 ?

like image 531
Fabien Avatar asked Nov 27 '13 09:11

Fabien


2 Answers

The std::max overloads are only for small sets known at compile time. What you need is std::max_element (which is even pre-11). This returns an iterator to the maximum element of a collection (or any iterator range):

auto max_iter = std::max_element(vd.begin(), vd.end());
// use *max_iter as maximum value (if vd wasn't empty, of course)
like image 91
Christian Rau Avatar answered Sep 18 '22 15:09

Christian Rau


Probably with lambda more flexibly

vector<data> vd;

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

You just should implement operator of compare for your type "data" via data::operator < ()

like image 32
angevad Avatar answered Sep 19 '22 15:09

angevad