Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call member function on object vector

Given a vector<Object>, where Object has a function run(), is there a way to call run() in a for_each, using only std functions/templates?

Note that run() is not a static function, it should actually transform the object being referenced (of course it's not the case in my small example)

I know the boost::lambda way

class Object
{
public:
    int run(){/* change object state */}
};

vector<Object> v(10);
for_each(v.begin(), v.end(), bind(&Object::run, _1));

but I am curious if it's a standard (non-Cxx11) way to do it.

like image 568
Sam Avatar asked Feb 20 '23 00:02

Sam


1 Answers

There is (was) C++03 way:

for_each(v.begin(), v.end(), mem_fun_ref(&Object::run));

See http://www.cplusplus.com/reference/std/functional/mem_fun_ref/

like image 165
PiotrNycz Avatar answered Feb 28 '23 07:02

PiotrNycz