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.
The comparator needs to return true if the first argument is less than the second, not the smaller of the two values. So the return statement should just be
return i1 < i2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With