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.
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.
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.
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.
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.
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}; 
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With