2009-09-21 55 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