函數配接器
阿新 • • 發佈:2018-01-20
進行 clas operator plus 參數 span int 常數 table 1. 定義:
STL中的函數配接器,能夠將函數子和另一個函數子、常數、普通函數結合起來。
STL中的函數配接器一共有4個,分別是:
bind1nd(op ,value) 相當於構成op(value,param),即把value結合成op的第一個參數;
bind2nd(op ,value) 相當於構成op(param,value),即把value結合成op的第二個參數;
not1(op) 相當於構成!op(param), 即op(param)的結果進行邏輯非運算;
not2(op) 相當於構成!op(param,param), 即把op(param,param)的結構進行邏輯非運算。
2. bind2nd應用舉例:
bind2nd可以配接函數子和另一個函數子、常數和普通函數。其中,普通函數作為bind2nd的第一個參數時,要用ptr_fun封裝該函數,使其變為函數子。
表達式 | 效果 |
bind1st(op,value) | op(value,param) |
bind2nd(op,value) | op(param,value) |
not1(op) | !op(param) |
not2(op) | !op(param1,param2) |
#include <iostream> #include<vector> #include <iterator> #include <algorithm> #include <functional> using namespace std; class PlusNum :public binary_function<int,int,void> { public: void operator()(int &x,int y) const { x += y; } }; void PlusInt(int x, int y) { cout<< x + y<<""; } int SubInt(int x, int y) { return x-y; } int main() { vector<int> vi = {1,4,6,2,5,7,9}; //bind2nd將常數和函數子配接。常數100作為 PlusNum函數子中operator(x,y)的第二個參數 y for_each(vi.begin(),vi.end(),bind2nd(PlusNum(), 100) ); copy(vi.begin(),vi.end(),ostream_iterator<int>(cout," ")); cout<<endl; //bind2nd將普通函數和函數子配接。函數 SubInt()的返回值作為 PlusNum函數子中operator(x,y)的第二個參數 y for_each(vi.begin(),vi.end(),bind2nd(PlusNum(), SubInt(1010,10)) ); copy(vi.begin(),vi.end(),ostream_iterator<int>(cout," ")); cout<<endl; //用ptr_fun將一個函數適配成一個函數子,再用bind2nd將其與常數結合。 for_each(vi.begin(),vi.end(),bind2nd(ptr_fun(PlusInt),1000) ); return 0; }
函數配接器