是否可以在C ++中将文字值传递给Lambda一元谓词? [英] Is it possible to pass a literal value to a lambda unary predicate in C++?

查看:115
本文介绍了是否可以在C ++中将文字值传递给Lambda一元谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下在地图上进行反向查找的代码:

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";

是否可以传递文字值(在这种情况下为3),而不必将其存储在变量(即findVal)中,以便可以通过捕获列表对其进行访问?

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?

在这种情况下,明显的限制之一是lambda充当一元谓词的角色,因此我无法在括号之间传递它.

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.

谢谢

推荐答案

您可以这样写:

 Pair v = *find_if(m.begin(), m.end(), [](const Pair & p) {
    return p.second == 3;
 });

您无需先捕获它.

顺便说一句,您不应假定std::find_if将找到该元素.更好的方法是使用迭代器:

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
 }

这篇关于是否可以在C ++中将文字值传递给Lambda一元谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆