Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a object's member function as a unary_function for std algorithms?

Tags:

c++

stl

I have a class that looks like this.

class A 
{
public:
    void doSomething();
}

I have an array of these classes. I want to call doSomething() on each item in the array. What's the easiest way to do this using the algorithms header?

like image 958
bradtgmurray Avatar asked Feb 28 '23 23:02

bradtgmurray


1 Answers

Use std::mem_fun_ref to wrap the member function as a unary function.

#include <algoritm>
#include <functional>

std::vector<A> the_vector;

...

std::for_each(the_vector.begin(), the_vector.end(),
              std::mem_fun_ref(&A::doSomething));

You can also use std::mem_fun if your vector contains pointers to the class, rather than the objects themselves.

std::vector<A*> the_vector;

...

std::for_each(the_vector.begin(), the_vector.end(),
              std::mem_fun(&A::doSomething));
like image 67
bradtgmurray Avatar answered Mar 28 '23 09:03

bradtgmurray