tags:

views:

161

answers:

1

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?

+8  A: 

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));
bradtgmurray
To be accurate, in your second example, the vector doesn't contain references, but objects/instances. The 'ref' in mem_fun_ref indicates that the method will be converted to a function that takes as parameter a reference to an instance. With mem_fun, the function takes a pointer.
Luc Touraille
Effective STL is your friend -- READ IT