Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+;中是否可以将文字值传递给lambda一元谓词+;?_C++_C++11_Lambda_Literals_Unary Function - Fatal编程技术网

C++ 在C+;中是否可以将文字值传递给lambda一元谓词+;?

C++ 在C+;中是否可以将文字值传递给lambda一元谓词+;?,c++,c++11,lambda,literals,unary-function,C++,C++11,Lambda,Literals,Unary Function,给定以下在地图上执行反向查找的代码: 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 &

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

    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";
map m={{'a',1},{'b',2},{'c',3},{'d',4},{'e',5};
int findVal=3;
对v=*查找if(m.begin(),m.end(),[findVal](常量对&p){
返回p.second==findVal;
});
你可以这样写:

 Pair v = *find_if(m.begin(), m.end(), [](const Pair & p) {
    return p.second == 3;
 });
您不需要首先捕获它

顺便说一句,如果
将找到元素,则不应假定
std::find_。更好的方法是使用迭代器:

 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++,因为它不使用20年,所以我有相当一点生锈,几乎没有接触到C++ 11。但是从根本上讲,你不需要一个变量名。如果它是一个文本,你无论如何也不能修改它,我想让我感到不舒服的是这个特定场景中一元谓词方面的局限性。显然,如果这不是一个限制,这将是很容易的,因为我可以把它作为一个论点来传递。我应该想一想我是如何提出更多的问题的。我实际上是在寻找一种方法,如果lambda是在其他地方定义的,而你不能将文本放入正文中。我认为这是不可能的,因为我已经怀疑,@aaronman在上面指出了这个原因(也就是说,没有可以访问它的变量名)。如果是这样的话,我会把这个标记为答案,因为它回答了我最初提出的问题。谢谢