Using std::max_element on a vector<double>

synaptik picture synaptik · Apr 15, 2012 · Viewed 112.2k times · Source

I'm trying to use std::min_element and std::max_element to return the min and max elements in a vector of doubles. My compiler doesn't like how I'm currently trying to use them, and I don't understand the error message. I could of course write my own procedure to find the min/max, but I'd like to understand how to use the functions.

#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char** argv) {

    double cLower, cUpper;
    vector<double> C;

    // code to insert values in C not shown here

    cLower = min_element(C.begin(), C.end());
    cUpper = max_element(C.begin(), C.end());

    return 0;
}

Here is the compiler error:

../MIXD.cpp:84: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
../MIXD.cpp:85: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment

Would someone please explain what I'm doing wrong?

Answer

David Schwartz picture David Schwartz · Apr 15, 2012

min_element and max_element return iterators, not values. So you need *min_element... and *max_element....