如何使用binder2nd,bind2nd和bind1st? 更具體何時使用它們,是否有必要? 另外,我正在尋找一些例子。如何使用binder和bind2nd函子?
1
A
回答
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))
無需任何輔助函子類需要定義!)
1
粘合劑是C++的方式做currying。順便說一句,檢查出Boost Bind庫
相關問題
- 1. find_if與bind2nd和函子
- 2. 如何使用bind1st和bind2nd?
- 3. 使用bind1st或bind2nd?
- 4. bind1st和bind2nd
- 5. 與bind2nd和binary_function
- 6. 問題使用bind1st和bind2nd與改造
- 7. 使用std :: bind2nd與引用
- 8. boost :: trim和std :: bind2nd
- 9. 使用std :: bind2nd與推力
- 10. ContentProvider和Binder IPC
- 11. bind2nd for_each循環
- 12. 如何使用GwtTestCase使用ui binder測試gwt複合組件?
- 13. 如何使用Binder在我的C#函數中執行動態綁定?
- 14. C++如何使用函子使用std :: mutex和std :: lock_guard?
- 15. 使用Android Binder類有什麼意義?
- 16. 使用JSON.net Binder/TypeNameHandling嵌套類型
- 17. 使用Binder進行表單驗證
- 18. 如何做Spring Cloud Steam Binder SPI韌性?
- 19. 如何瞭解Android Binder遞歸
- 20. 使用gwt和ui-binder在懸停上更改圖像
- 21. ASCII字符Binder
- 22. JavaBinder FAILED BINDER TRANSACTION
- 23. 如何使用Python win32com調用Excel VBA函數和子集?
- 24. 的for_each bind2nd mem_fun VS 2005
- 25. Bind2nd問題與用戶定義的類
- 26. 如何在javascript中使用函子
- 27. 如何使用STL編寫函子?
- 28. Android,JUnit測試和失敗的BINDER TRANSACTION
- 29. 如何在Google電子表格中使用函數CONCATENATE和IMPORTRANGE?
- 30. Binder到字符串
對,我明白,但是這是怎麼回事? 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
對不起,我沒有格式化代碼,但是代碼這裏: http://www.cplusplus.com/reference/algorithm/count_if/ – Tom 2009-09-21 16:50:21
@Tom,是的,在簡單的例子中,函子可以是一個函數,但是,你必須先定義它遠離使用的地方) - 活頁夾很方便,因爲它們可以讓你避免這種情況(從來沒有必要_,正如我已經說過的:只是_convenient _! - )。 – 2009-09-21 17:04:42