Search code examples
c++c++11lambdaliteralsunary-function

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 (i.e. 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


Solution

  • 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
     }