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

旧街凉风 提交于 2020-02-24 09:22:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!