Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using member variable as predicate

Tags:

c++

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.

like image 818
thorsan Avatar asked Oct 26 '25 14:10

thorsan


2 Answers

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);
like image 151
Jarod42 Avatar answered Oct 29 '25 03:10

Jarod42


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));
like image 44
Maxim Egorushkin Avatar answered Oct 29 '25 05:10

Maxim Egorushkin