Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ lambda expression in std::find_if?

Tags:

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

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.

like image 593
Anti-Distinctlyminty Avatar asked May 03 '13 20:05

Anti-Distinctlyminty


People also ask

What does Find_if return?

C++ Algorithm find_if() function returns the value of the first element in the range for which the pred value is true otherwise the last element of the range is given.

How do you make a lambda expression in C++?

Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.

Does C have lambda expression?

No, C doesn't have lambda expressions (or any other way to create closures). This is likely so because C is a low-level language that avoids features that might have bad performance and/or make the language or run-time system more complex.

What does [=] mean in lambda function?

The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created.


2 Answers

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 i and take a as an argument:

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

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

struct {    LWItemID i;    auto operator()(LWItem a) -> bool { return a->GetID()==i; }  } lambda = {i}; 
like image 94
ecatmur Avatar answered Sep 19 '22 12:09

ecatmur


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.

like image 36
Jiwan Avatar answered Sep 20 '22 12:09

Jiwan