Fabien
Fabien

Reputation: 13406

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 ?

Upvotes: 8

Views: 5427

Answers (2)

angevad
angevad

Reputation: 317

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

Upvotes: 2

Christian Rau
Christian Rau

Reputation: 45948

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)

Upvotes: 19

Related Questions