std::find_if 中的 C++ lambda 表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16366735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:18:10  来源:igfitidea点击:

C++ lambda expression in std::find_if?

c++algorithmc++11stllambda

提问by Anti-Distinctlyminty

I've got a std::map that contains a class and that class has an id. I have an id that I'm trying to find in the set

我有一个 std::map 包含一个类,并且该类有一个 id。我有一个我想在集合中找到的 ID

typedef std::set<LWItem> ItemSet;
ItemSet selectedItems;
LWItemID i = someID;

ItemSet::iterator isi;
isi = std::find_if(selectedItems.begin(), selectedItems.end(), [&a](LWItemID i)->bool { return a->GetID()==i; } 

I get an error saying that the lambda capture variable is not found, but I have no idea what I'm supposed to do to get it to capture the container contents as it iterates through. Also, I know that I cant do this with a loop, but I'm trying to learn lambda functions.

我收到一条错误消息,说找不到 lambda 捕获变量,但我不知道我应该怎么做才能让它在迭代时捕获容器内容。另外,我知道我不能用循环来做到这一点,但我正在尝试学习 lambda 函数。

回答by ecatmur

You've got your capture and argument reversed. The bit inside the []is the capture; the bit inside ()is the argument list. Here you want to capture the local variable iand take aas an argument:

你已经把你的捕获和论点颠倒了。里面的位[]是捕获;里面的位()是参数列表。在这里,您要捕获局部变量i并将其a作为参数:

[i](LWItem a)->bool { return a->GetID()==i; } 

This is effectively a shorthand for creating a functor class with local variable i:

这实际上是创建带有局部变量的函子类的简写i

struct {
   LWItemID i;
   auto operator()(LWItem a) -> bool { return a->GetID()==i; } 
} lambda = {i};

回答by Jiwan

From what i understand you code should look like this :

据我了解,您的代码应如下所示:

auto foundItem = std::find_if(selectedItems.begin(), selectedItems.end(), 
[&i](LWItem const& item) 
{ 
return item->GetID() == i; 
});

This will capture the LWItem that have an ID equal to i, with i being a previosuly declared ID.

这将捕获 ID 等于 i 的 LWItem,其中 i 是先前声明的 ID。