How can I get the max (or min) value in a vector?

bob blob picture bob blob · Mar 26, 2012 · Viewed 309.7k times · Source

How can I get the max (or min) value in a vector in C++?

I have seen a few solutions for this on Google but none of them made sense to me :(

Can someone explain in an easy straightforward noob way how to get the max or min value from a vector please? 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 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]’

EDIT: I was not able to answer my own ??? so I'll put it here...

Wow, thanks for the fast replies! I ended up doing it this way, do think its ok?

for (unsigned int i = 0; i < cdf.size(); i++)
  if (cdf[i] < cdfMin)
    cdfMin = cdf[i];

where cdf is a vector.

Answer

sehe picture sehe · Mar 26, 2012

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 :/