程序员自定义的functor要使用bind1st bind2nd函数,需要提供binder接口。如何提供这个接口,就要继承自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的第一个实参,bind2nd绑定第二个实参。
示例: 删除vector中所有能被某数整除的元素
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对binder的实现中,要求不能改变实参。只有符合const操作的自定义functor才能使用bind1st和bind2nd绑定参数