I am trying to find an object in a vector of objects whos value of a member variable is true. Could it be done without defining a lamba function or function object, by just specifying the member variable itself:
class A
{
public:
explicit A(bool v, int v2, float v3) : value(v), value2(v2), value3(v3)
{}
...
bool value;
int value2;
float value2;
...
}
int main()
{
std::vector<A> v;
v.push_back(A(false, 1, 1.0));
v.push_back(A(true, 2, 2.0));
v.push_back(A(false, 3, 3.0));
auto iter = std::find_if(v.begin(), v.end(), &A::value);
}
Compiling as is above does not work as it assumes a A* and not A.
Not that its a problem to use lambdas, just curious.
You may use std::mem_fn
auto iter = std::find_if(v.begin(), v.end(), std::mem_fn(&A::value));
Demo
Note that range library should allow directly:
auto iter = range::find_if(v, &A::value);
If you cannot use C++11 lambdas, you can do that with std::bind:
auto iter = std::find_if(v.begin(), v.end(), std::bind(&A::value, std::placeholders::_1));
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