tags:

views:

405

answers:

3

Hi

I have to pass the address of a member fn taking one argument to the std::for_each. how do i do this?

class A{

void load()
{
vector<int> vt(10,20);
std::for_each(vt.begin(), vt.end(), &A::print); 
//It didnt work when i tried mem_fun1(&A::print)
}

void print(int a)
{
cout<<a;
}

};

Thanks

+4  A: 

What you have in vt are integers not objects of type A. Also, print doesn't manipulate any of the member variables, just make it static:

class A{

void load()
{
vector<int> vt(10,20);
std::for_each(vt.begin(), vt.end(), A::print); // static functions are regular functions
}

static void print(int a)
{
cout<<a;
}

};
AraK
+4  A: 

When using std::mem_fun, you have to pass pointer to class as first argument. You can bind it in this case with std::bind1st.

class A
{
public:
    void print(int v) {std::cout << v;}

    void load()
    {   
        std::vector<int> vt(10, 20);

        std::for_each(vt.begin(), vt.end(), std::bind1st(std::mem_fun(&A::print), this));
    }
}
Dotti
Problem is, mem_fun would be to apply it on A instances, but vt contains `int`s as pointed by AraK.
Matthieu M.
@Matthieu: No, `mem_fun` turns the method into a binary functor. bind1st takes a binary functor and turns it into a unary functor. In this case the `mem_fun` arguments are `A*` and `int`; binding `this` as the first argument leaves a unary functor taking an `int` as intended.
MSalters
+2  A: 

I find boost::bind helpful. That way I don't have to remember all the rules associated with std::mem_fun.

#include <boost/bind.hpp>
class A{

void load()
{
  vector<int> vt(10,20);
  std::for_each(vt.begin(), vt.end(), boost::bind(&A::print,this,_1)); 
}

void print(int a)
{
  cout<<a;
}   
};

Though in this particular case, I would prefer the copy to ostream_iterator idiom:

copy(vt.begin(), vt.end(), ostream_iterator<int>(cout, " "));
Dan Hook