binary_function 函数用法

在定义一个仿函数(functor)不会使用binary_function,但是如果需要函数适配器便需要使用它实现:

struct Inserter
{
    void operator() (int n, vector<int>& v)
        {
            v.push_back(n);
        }
}
Inserter cIn;
vector<int> vInt;
cln(2, vInt);

通过一个算法忘当前容器追加值:

template<typename Functor>
void append(Functor f)
{
    int x;
    while(cin >> x)
        f(x);
}

此时,append的Functor只有一个形参,在不考虑重写Inserter的基础上我们需要定义Inserter_adapter:

template<typename Functor>
struct Inserter_Adapter
{
    Inserter_Adapter(const Functor& f, vector<int>& v)
        :_f(f), _v(v)
           {}
    void operator()(int x)
        {
            _f(x, v_);
        }

    private:
        Functor& _f;
        vector<int> _v;
};
//使用:
Inserter cIn;
vector<int> vIn;
Inserter_Adapter cIna(f, vIn);
append(ia);

在STL中,提供了相关的函数 bind2nd的适配器,把第二个参数绑定让一个二元函数变成一元的。 此前定义的Inserter不能直接使用在bind2nd上,因为和bind2nd的concept不符合,需要继承binary_function:

struct Inserter : public std::binary_function<int, vector<int>&, void>
{
    void operator()(int x, vector<int>& vIn)
        {
            v.push_back(x);
        }
}
Inserter cIn;
vector<int> vIn;
append(std::bind2nd(cIn, vd))     //1
Inserter_Adapter(cIn, vd)

转载于:https://my.oschina.net/zhaolu0607/blog/826953

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值