C++ STL for_each 应该采用指向带有一个参数的成员函数的指针
我必须将带有一个参数的成员 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 std::mem_fun 时,必须将指向类的指针作为第一个参数传递。在这种情况下,您可以使用 std::bind1st 绑定它。
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.
vt
中的内容是整数,而不是A
类型的对象。此外,print
不会操作任何成员变量,只需将其设置为static
:What you have in
vt
are integers not objects of typeA
. Also,print
doesn't manipulate any of the member variables, just make itstatic
:我发现 boost::bind 很有帮助。这样我就不必记住与 std::mem_fun 相关的所有规则。
尽管在这种特殊情况下,我更喜欢使用 ostream_iterator 惯用法的副本:
I find boost::bind helpful. That way I don't have to remember all the rules associated with std::mem_fun.
Though in this particular case, I would prefer the copy to ostream_iterator idiom: