我无法理解 mem_fun_ref
。我必须承认,我通常将仿函数用于此类事情,因为它们可以内联以提高速度和利润。但是,这段代码不会成为瓶颈,所以我想尝试一下。
这是我想做的一个例子。我知道还有其他方法可以做到这一点。我不想使用 copy
,我不想使用范围成员函数,我不想使用 back_inserter
。我特别想使用 mem_fun_ref
。这只是一个简单的例子,实际情况要复杂得多。也就是说,我真的不知道为什么这是错误的,但我不熟悉 mem_fun_ref
或 mem_fun
。
这是我想要的工作:
#include <list>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
list<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
vector<int> b;
// should work like magic!
for_each(a.begin(), a.end(), bind1st(mem_fun_ref(&vector<int>::push_back), b));
}
但是我得到了 3 个错误:
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(276) : error C2529: '_Right' : reference to reference is illegal
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(281) : error C2529: '_Right' : reference to reference is illegal
1>c:\program files\microsoft visual studio 9.0\vc\include\functional(282) : error C2535: 'void std::binder1st<_Fn2>::operator ()(const int &(&)) const' : member function already defined or declared
1> with
1> [
1> _Fn2=std::mem_fun1_ref_t<void,std::vector<int>,const int &>
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\functional(276) : see declaration of 'std::binder1st<_Fn2>::operator ()'
1> with
1> [
1> _Fn2=std::mem_fun1_ref_t<void,std::vector<int>,const int &>
1> ]
reference to reference is illegal
让我觉得函数需要按值获取参数。但是当然,这在 vector
中是不可能改变的,而且在我的代码中也不可能改变它。是否有一个简单的改变来让它工作?我需要一个 1-liner 的解决方案。
最佳答案
只需使用绑定(bind)
。 mem_fun
版本太难了。
for_each(a.begin(), a.end(),
boost::bind(&vector<int>::push_back, boost::ref(b), _1));
另一种不需要使用 ref
的方法是传递指向要修改的 vector 的指针:
for_each(a.begin(), a.end(),
boost::bind(&vector<int>::push_back, &b, _1));
关于c++ - mem_fun_ref 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/949047/