Search code examples
c++c++11stdinitializer-list

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 ?


Solution

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