25

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.

3
  • 2
    Where did you declare a? What are you searching in? map or set? Commented May 3, 2013 at 20:08
  • selectedItems is a container of LWItems, so the lambda can't take an LWItemID as an argument. It has to take an LWItem (possible a const &) Commented May 3, 2013 at 20:13
  • Apologies if it seems like a stupid question. My main problem seemed to be that I wasn't sure how to capture the local LWItem variable, i, and the element being iterated via std::find_if. Commented May 4, 2013 at 10:00

2 Answers 2

29

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}; 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. This'll teach me to try and code when I'm super tired (though I never seem to learn).
14

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.