简体   繁体   中英

Is it possible to pass a literal value to a lambda unary predicate in C++?

Given the following code that does a reverse lookup on a map:

    map<char, int> m = {{'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}};

    int findVal = 3;
    Pair v = *find_if(m.begin(), m.end(), [findVal](const Pair & p) {
        return p.second == findVal;
    });
    cout << v.second << "->" << v.first << "\n";

Is it possible to pass a literal value (in this case 3) instead of having to store it in a variable (ie findVal) so that it can be accessed via the capture list?

Obviously one of the constraints in this case is that the lambda is filling the role of a unary predicate so that I can't pass it between the parentheses.

Thanks

You can write this:

 Pair v = *find_if(m.begin(), m.end(), [](const Pair & p) {
    return p.second == 3;
 });

You don't need to capture it to begin with.

BTW, you should not assume std::find_if will find the element. A better way is to use iterator:

 auto it = find_if(m.begin(), m.end(), [](const Pair & p) {
              return p.second == 3;
           });
 if (it == m.end() ) { /*value not found*/ }

 else {
     Pair v = *it;
     //your code
 }

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