程序員自定義的functor要使用bind1st bind2nd函數(shù),需要提供binder接口。如何提供這個(gè)接口,就要繼承自unary_function<> binary_function。
user defined functors must satisfy 3 requirements to use bind1st and bind2nd
1.include functional
2.operator must be const
3.inherited from binary_function
顧名思義,bind1st綁定functor的第一個(gè)實(shí)參,bind2nd綁定第二個(gè)實(shí)參。
示例: 刪除vector中所有能被某數(shù)整除的元素
struct Del : public binary_function<int, int, bool> {
bool operator()(const int& x, const int& del) const { return x % del == 0 ? true : false;}
};
...
vec.erase(remove(vec.begin(), vec.end(), bind2nd(Del(), 3)), vec.end());
...
注意:重載必須指明 const
bool operator() (const T& lhs, const T& rhs) const{}
在STL對(duì)binder的實(shí)現(xiàn)中,要求不能改變實(shí)參。只有符合const操作的自定義functor才能使用bind1st和bind2nd綁定參數(shù)