說明
bind1st()
和 bind2nd()
,在 C++11 里已經 deprecated 了,建議使用新標准的 bind()
。
下面先說明bind1st()
和 bind2nd()
的用法,然后在說明bind()
的用法。
頭文件
#include <functional>
作用
bind1st()
和bind2nd()
都是把二元函數轉化為一元函數,方法是綁定其中一個參數。
bind1st()
是綁定第一個參數。
bind2nd()
是綁定第二個參數。
例子
#include <iostream> #include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind2nd(less<int>(), 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind1st(less<int>(), 40)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }
There are 4 elements that are less than 40. There are 1 elements that are not less than 40.
分析
less()
是一個二元函數,less(a, b)
表示判斷a<b
是否成立。
所以bind2nd(less<int>(), 40)
相當於x<40
是否成立,用於判定那些小於40的元素。
bind1st(less<int>(), 40)
相當於40<x
是否成立,用於判定那些大於40的元素。
bind()
bind1st()
和 bind2nd()
,在 C++11 里已經 deprecated 了.bind()
可以替代他們,且用法更靈活更方便。
上面的例子可以寫成下面的形式:
#include <iostream> #include <algorithm> #include <functional> using namespace std; int main() { int numbers[] = { 10,20,30,40,50,10 }; int cx; cx = count_if(numbers, numbers + 6, bind(less<int>(), std::placeholders::_1, 40)); cout << "There are " << cx << " elements that are less than 40.\n"; cx = count_if(numbers, numbers + 6, bind(less<int>(), 40, std::placeholders::_1)); cout << "There are " << cx << " elements that are not less than 40.\n"; system("pause"); return 0; }
std::placeholders::_1
是占位符,標定這個是要傳入的參數。
所以bind()
不僅可以用於二元函數,還可以用於多元函數,可以綁定多元函數中的多個參數,不想綁定的參數使用占位符表示。
此用法更靈活,更直觀,更便捷。
參考
http://www.cplusplus.com/reference/functional/bind1st/
http://www.cplusplus.com/reference/functional/bind2nd/
http://www.cplusplus.com/reference/functional/bind/
作者:book_02
鏈接:https://www.jianshu.com/p/f337f42822fe
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。