2009-11-05 72 views

回答

4

使用的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)); 
    } 
} 
+0

问题是,mem_fun将其应用在一个实例,但VT包含'int's尖的由AraK提供。 – 2009-11-05 08:25:50

+0

@Matthieu:不,mem_fun将方法转换为二进制函子。 bind1st接受一个二元函子,并将其变成一个一元函子。在这种情况下,'mem_fun'参数是'A *'和'int';作为第一个参数绑定'this'会留下一个一元函数,并且按照预期的那样采用'int'。 – MSalters 2009-11-05 09:00:31

4

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

}; 
3

我发现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, " "));