Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::min_element returning unexpected result

Tags:

c++

std

c++11

min

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.

like image 582
Javi Avatar asked Jun 13 '26 05:06

Javi


1 Answers

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;
like image 186
Mike Seymour Avatar answered Jun 17 '26 13:06

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!