简体   繁体   中英

C++: Issue with lambda function and capture list

I have the following function:

double mn = 2.0;
double mx = 5.0;
auto isBetween = [&,mx,mn](double y) -> bool{
    if (mn<y<mx) {
        return true;
    } else {
        return false;
    }
};

However, when I debug, all of the values I pass as double y return true.

Is there anything that I am missing?

Your test if (mn<y<mx) isn't what you want.

You want something like: if (mn < y && y < mx) instead.

In C++, the < operator cannot be chained the way it can in mathematics. In the expression (mn < y < mx) , (mn < y) evaluates to either 1 (true) or 0 (false), and from there the expression is equivalent to 1 < mx or 0 < mx .

Your Problem is here (mn<y<mx) , which can be read as

(mn < y) < mx

This means, that first mn < y is evaluated, which leads in a result of type bool and is either ture or false . The result is finally compared to mx .

What you tried to do is to check, if mn < y and y < mx , what has to be expressed like this:

if (mn<y && y<mx)

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