schorsch312
schorsch312

Reputation: 5698

Find minimum and maximum of a long vector

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

I could use an old fashioned for loop, but I wonder if there is an elegant (c++11, std) way of doing it.

#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


}

Upvotes: 3

Views: 163

Answers (1)

BoBTFish
BoBTFish

Reputation: 19757

You mean like 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 this assumes the range is not empty (as does your existing solution), else the iterator dereferences are Undefined Behaviour.

Also note this is not quite the same as your solution, as max_element returns the first largest element, and minmax_element returns the last largest element. E.g.

1 2 1 2
  ^   ^
  A   B

Where A is found by your solution, and B is found by mine. (This is for reasons of stability; Alex Stepanov got the definition of max wrong in the original STL.)

Upvotes: 6

Related Questions