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

1

3

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

Bide answered 7/11, 2013 at 5:21 Comment(4)
How would you access it then?Sheya
Therein lies the rub. I didn't think it was possible for just that reason so I thought I'd ask just in case I was missing something. I only have a couple of months back with C++ after not using it for ~20 years so I have quite a bit of rust and almost no exposure to C++ 11.Bide
But it fundamentally makes no sense you need a variable name. If it's a literal you can't modify it anywaySheya
I think what's throwing me off here is the limitation of the unary predicate aspect of this particular scenario. Obviously this would be easy if that wasn't a constraint since I could just pass it in as an argument.Bide
B
1

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
 }
Borchert answered 7/11, 2013 at 5:28 Comment(1)
I should have thought out how I asked my question more. I was actually looking for a way to do this if the lambda was defined elsewhere where you couldn't put the literal in the body. I'm thinking that it can't be done for the reason that I already suspected and that @Sheya pointed out above (i.e. no variable name with which to access it). If this is the case then I will mark this as the answer since it answers my question as originally asked. Thanks.Bide

© 2022 - 2024 — McMap. All rights reserved.