Find the minimum and maximum long vector

I want to find the minimum and maximum of a long vector. The following code works, but I need to traverse the vector twice.

I could use the old form for the loop, but I'm wondering if there is an elegant (C ++ 11, std) way to do this.

#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char** argv) {
     vector<double> C;

     // code to insert values in C not shown here

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

     // code using cLower and cUpper


}

      

+3


source to share


1 answer


Do you mean std::minmax_element

?

auto mm = std::minmax_element(std::begin(c), std::end(c));
const double cLower = *mm.first;
const double cUpper = *mm.second;

      

Note that this assumes the range is not empty (as is the existing solution), otherwise the iterators will have Undefined Behavior .



Also note that this is not the same as your solution, as it max_element

returns the first largest element, but minmax_element

returns the last largest element. For example.

1 2 1 2
  ^   ^
  A   B

      

Where A

found by your solution, but B

found by me. (This is for stability reasons; Alex Stepanov got the definition max

wrong in the original STL
.)

+6


source







All Articles