C++ STL for_each 应该采用指向带有一个参数的成员函数的指针

发布于 2024-08-10 17:51:57 字数 291 浏览 2 评论 0原文

我必须将带有一个参数的成员 fn 的地址传递给 std::for_each。我该怎么做?

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

};

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

两人的回忆 2024-08-17 17:51:57

使用 std::mem_fun 时,必须将指向类的指针作为第一个参数传递。在这种情况下,您可以使用 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));
    }
}

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));
    }
}
旧时浪漫 2024-08-17 17:51:57

vt 中的内容是整数,而不是 A 类型的对象。此外,print 不会操作任何成员变量,只需将其设置为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;
}

};

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

};
风为裳 2024-08-17 17:51:57

我发现 boost::bind 很有帮助。这样我就不必记住与 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;
}   
};

尽管在这种特殊情况下,我更喜欢使用 ostream_iterator 惯用法的副本:

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

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, " "));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文