2009-09-21 52 views

回答

5

他们从来没有,严格来说,必要,因为你总是可以定义自己的自定义函数对象;但他们非常方便正是为了避免必须在简单情况下定义自定义函子。例如,假设您想要计算std::vector<int>> 10中的项目。你当然可以...代码:

std::count_if(v.begin(), v.end(), gt10()) 

定义后:

class gt10: std::unary_function<int, bool> 
{ 
public: 
    result_type operator()(argument_type i) 
    { 
     return (result_type)(i > 10); 
    } 
}; 

但考虑如何更方便的是代码,而不是:

std::count_if(v.begin(), v.end(), std::bind1st(std::less<int>(), 10)) 

无需任何辅助函子类需要定义!)

+0

对,我明白,但是这是怎么回事? bool IsOdd(int i){return((i%2)== 1); } int main(){ int mycount; vector myvector; (int i = 1; i <10; i ++)myvector.push_back(i); // myvector:1 2 3 4 5 6 7 8 9 mycount =(int)count_if(myvector.begin(),myvector.end(),IsOdd); cout <<“myvector包含”<< mycount <<“奇数值。\ n”; return 0; } 这是从:http://www.cplusplus.com/reference/algorithm/count_if/ 他们没有定义任何仿的对象,只是一个简单的功能 – Tom 2009-09-21 16:49:34

+0

对不起,我没有格式化代码,但是代码这里: http://www.cplusplus.com/reference/algorithm/count_if/ – Tom 2009-09-21 16:50:21

+0

@Tom,是的,在简单的例子中,函子可以是一个函数,但是,你必须先定义它远离使用的地方) - 活页夹很方便,因为它们可以让你避免这种情况(从来没有必要_,正如我已经说过的:只是_convenient _! - )。 – 2009-09-21 17:04:42