I am trying to use std::find_if to find an object that matches some criteria. Consider the following:
struct MyStruct
{
MyStruct(const int & id
This is where the lambda capture comes into play. Besides saying what type of parameters are to be passed to the lambda you can also say what existing variables are to be used to construct the lambda with. So in this case you would have something like
std::vector<MyStruct>::iterator i = std::find_if(myVector.begin(),
myVector.end(),
[&](const auto& val){ return val.m_id == toFind.m_id; } );
So the [&]
says capture all variables used in the body of the lambda by reference. The (const auto& val)
makes the operator()
of the lambda a template and lets you take in any type. Then in the body we compare what is passed in from find_if
to toFind
.
Try this:
std::find_if(
myVector.begin(), myVector.end(),
[&toFind](const MyStruct& x) { return x.m_id == toFind.m_id;});
Alternatively, if you had defined an appropriate ==
overload for MyStruct
, you could just use find
:
std::find(myVector.begin(), myVector.end(), toFind); // requires ==
The find_if
version is usually best when you have some kind of heterogeneous lookup, for example if you were just given an int
, not a value of MyStruct
.
Do as following:
std::find_if(myVector.begin(), myVector.end(),
[&toFind] (const auto &ele) { return ele.m_id == toFind.m_id}; );
You may use the following:
MyStruct toFind(1);
std::vector<MyStruct>::iterator i =
std::find_if(myVector.begin(), myVector.end(),
[&](const auto& e) { return e.id == toFind.id; });