C++ – How to get the maximum or minimum value in a vector

cmaxminvector

How can I get the maximum or minimum value in a vector in C++?

And am I wrong in assuming it would be more or less the same with an array?

I need an iterator, right? I tried it with max_element, but I kept getting an error.

vector<int>::const_iterator it;
it = max_element(cloud.begin(), cloud.end());
error: request for member ‘begin’ in ‘cloud’, which is of non-class type ‘int [10]’

Best Answer

Using C++11/C++0x compile flags, you can

auto it = max_element(std::begin(cloud), std::end(cloud)); // C++11

Otherwise, write your own:

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

See it live at http://ideone.com/aDkhW:

#include <iostream>
#include <algorithm>

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

int main()
{
    const int cloud[] = { 1,2,3,4,-7,999,5,6 };

    std::cout << *std::max_element(mybegin(cloud), myend(cloud)) << '\n';
    std::cout << *std::min_element(mybegin(cloud), myend(cloud)) << '\n';
}

Oh, and use std::minmax_element(...) if you need both at once :/