Using std :: max_element for a vector <double>
I am trying to use std::min_element and std::max_element to return the minimum and maximum elements in a doubles vector. My compiler does not like how I am currently trying to use them, and I do not understand the error message. I could, of course, write my own procedure to find min / max, but I would like to understand how to use 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 Can someone please explain what I am doing wrong?
min_element and max_element return iterators, not values. Therefore, you need *min_element... and *max_element...
As others have said, std::max_element() and std::min_element() return the iterators that need to be dereferenced to get the value.
The advantage of returning an iterator (and not just a value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C ++ 11 for short):
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0}; auto biggest = std::max_element(std::begin(v), std::end(v)); std::cout << "Max element is " << *biggest << " at position " << std::distance(std::begin(v), biggest) << std::endl; auto smallest = std::min_element(std::begin(v), std::end(v)); std::cout << "min element is " << *smallest << " at position " << std::distance(std::begin(v), smallest) << std::endl; } This gives:
Max element is 5 at position 4 min element is 1 at position 0 Note:
Using std::minmax_element() , as suggested in the comments above, may be faster for large datasets, but may give slightly different results. The values ββfor my example above will be the same, but the position of the "max" element will be 9 , because ...
If multiple elements are equivalent to the largest element, an iterator is returned to the last such element.
min / max_element returns an iterator in the min / max element, not the value of the min / max element. You must dereference the iterator to get the value and assign it to the double. I.e:
cLower = *min_element(C.begin(), C.end());