开发者

C++ STL for_each should take pointer to member function taking one argument

I have to pass the address of a member fn taking one argument to the std::for_each. how do 开发者_StackOverflow社区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


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


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

};


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, " "));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜