简体   繁体   English

如何使用活页夹和bind2nd函子?

[英]how to use binder and bind2nd functors?

How to use binder2nd, bind2nd, and bind1st? 如何使用binder2nd,bind2nd和bind1st? More specifically when to use them and are they necessary? 更具体地说,何时使用它们,它们是否必要? Also, I'm looking for some examples. 另外,我正在寻找一些示例。

They're never, strictly speaking, necessary , as you could always define your own custom functor object; 从严格意义上讲,它们从来都不是必需的 ,因为您始终可以定义自己的自定义仿函数对象。 but they're very convenient exactly in order to avoid having to define custom functors in simple cases. 但是它们非常方便 ,以避免在简单情况下必须定义自定义函子。 For example, say you want to count the items in a std::vector<int> that are > 10 . 例如,假设您要计算std::vector<int>> 10 You COULD of course code...: 您当然可以使用代码...:

std::count_if(v.begin(), v.end(), gt10()) 

after defining: 定义后:

class gt10: std::unary_function<int, bool>
{
public:
    result_type operator()(argument_type i)
    {
        return (result_type)(i > 10);
    }
};

but consider how much more convenient it is to code, instead: 但请考虑编写代码更方便:

std::count_if(v.begin(), v.end(), std::bind1st(std::less<int>(), 10)) 

without any auxiliary functor class needing to be defined!-) 无需定义任何辅助函子类!-)

Binders are the C++ way of doing currying . 绑定程序是C ++进行currying的方法 BTW, check out Boost Bind library 顺便说一句,签出Boost Bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM