简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM