lundi 9 mars 2015

std::min_element returning unexpected result

I want to find the minimum of a vector:



#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main () {
vector<double> v{2, 0, 4};
double minT = *std::min_element(v.begin(), v.end(),
[](double i1, double i2) {
std::cout << "Comparing: " << i1 << " " << i2 << " " << ((i1 < i2)? i1:i2) << " " << '\n';
return (i1 < i2)? i1:i2;
});
cout << "Minimum is: " << minT << '\n';
}


But the output of this piece of code is:



Comparing: 0 2 0
Comparing: 4 2 2
Minimum is: 4


What am I doing wrong? Is there any undefined behaviour there?


NOTE: I know I do not need the lambda function. Removing it returns the expected result (0), but my goal is to have a personalized min function which does not consider zeros.


Aucun commentaire:

Enregistrer un commentaire