bradtgmurray
bradtgmurray

Reputation: 14313

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

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?

Upvotes: 4

Views: 503

Answers (1)

bradtgmurray
bradtgmurray

Reputation: 14313

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));

Upvotes: 8

Related Questions