Monday, April 25, 2011

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?

From stackoverflow
  • 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));
    
    Luc Touraille : 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.

0 comments:

Post a Comment