简体   繁体   English

std :: min_element返回意外结果

[英]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. 注意 :我知道我不需要lambda函数。 Removing it returns the expected result (0), but my goal is to have a personalized min function which does not consider zeros. 删除它会返回预期的结果(0),但我的目标是拥有一个不考虑零的个性化min函数。

The comparator needs to return true if the first argument is less than the second, not the smaller of the two values. 如果第一个参数小于第二个参数,则比较器需要返回true ,而不是两个值中较小的一个。 So the return statement should just be 所以返回语句应该是

return i1 < i2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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