How to call a member function of an object as 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 () for each element of an array. What is the easiest way to do this using the algorithm header?

+4
source share
1 answer

Use std :: mem_fun_ref to wrap a 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 and not the objects themselves.

 std::vector<A*> the_vector; ... std::for_each(the_vector.begin(), the_vector.end(), std::mem_fun(&A::doSomething)); 
+8
source

All Articles