从零开始学C++之STL(九):函数适配器bind2nd 、mem_fun_ref 源码分析、函数适配器应用举例

本文详细介绍了C++中的函数适配器,特别是bind2nd和mem_fun_ref的使用。通过源码分析,展示了如何将二元函数转换为一元函数对象,以及在实际应用中的示例,如计算容器中奇数或大于特定值的元素个数,并结合成员函数和一般函数展示了不同场景下的应用。
摘要由CSDN通过智能技术生成

一、适配器

三种类型的适配器:

容器适配器:用来扩展7种基本容器,利用基本容器扩展形成了栈、队列和优先级队列


迭代器适配器:(反向迭代器、插入迭代器、IO流迭代器)


函数适配器:函数适配器能够将仿函数和另一个仿函数(或某个值、或某个一般函数)结合起来。

针对成员函数的函数适配器

针对一般函数的函数适配器


二、函数适配器示例

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>

using  namespace std;

bool is_odd( int n)
{
     return n %  2 ==  1;
}

int main( void)
{
     int a[] = { 12345};
    vector< int> v(a, a +  5);

    cout << count_if(v.begin(), v.end(), is_odd) << endl;

     //计算奇数元素的个数
     // 这里的bind2nd将二元函数对象modulus转换为一元函数对象。
     //bind2nd(op, value) (param)相当于op(param, value)
    cout << count_if(v.begin(), v.end(),
                     bind2nd(modulus< int>(),  2)) << endl;


     //bind1st(op, value)(param)相当于op(value, param);
    cout << count_if(v.begin(), v.end(),
                     bind1st(less< int>(),  4)) << endl;

     return  0;
}

这里的bind2nd将二元函数对象modulus转换为一元函数对象。是如何做到的呢?跟踪源码就知道了。

首先,bind2nd 是一个模板函数,如下:

 C++ Code 
1
2
3
4
5
6
7
8
9
// TEMPLATE FUNCTION bind2nd
template <  class _Fn2,
          class _Ty >  inline
binder2nd<_Fn2> bind2nd( const _Fn2 &_Func,  const _Ty &_Right)
{
     // return a binder2nd functor adapter
     typename _Fn2::second_argument_type _Val(_Right);
     return (std::binder2nd<_Fn2>(_Func, _Val));
}


将匿名对象modulus<int>() 和 2 传递进去,返回值是 std::binder2nd<_Fn2>(_Func, _Val);  即是一个模板类对象,看binder2nd 模板类

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

// TEMPLATE CLASS bi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值