问题
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
回答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
}
来源:https://stackoverflow.com/questions/19828526/is-it-possible-to-pass-a-literal-value-to-a-lambda-unary-predicate-in-c