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

WXB13
  • 1,046
  • 3
  • 11
  • 17
  • 1
    How would you access it then? – aaronman Nov 07 '13 at 05:24
  • 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. – WXB13 Nov 07 '13 at 05:32
  • 1
    But it fundamentally makes no sense you need a variable name. If it's a literal you can't modify it anyway – aaronman Nov 07 '13 at 05:35
  • 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. – WXB13 Nov 07 '13 at 06:01

1 Answers1

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
 }
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 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 @aaronman 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. – WXB13 Nov 07 '13 at 05:58