STL binder自定义functor

程序员自定义的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才能使用bind1stbind2nd绑定参数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容