STL之仿函数

1、基本概念

  仿函数,顾名思义,仿照函数的使用形式,但本质上是一个类模板。通过重载运算符(),通过类模板生成的模板类就可以像函数一样使用。STL设计仿函数,可以让算法采用不同的策略,从而使算法更加的灵活。

2、相应型别

  STL为了统一仿函数,定义了一元函数和二元函数的参数类型及返回值类型,但不支持三元函数。每个定义的仿函数对应进行继承,就可以相同的手法获得仿函数的参数类型和返回值类型。

3、算术类仿函数

  这类仿函数,提供基本的算术运算,示例如下:

//算术类仿函数
cout<<plus<int>()(3,5)<<endl;
cout<<minus<int>()(3,5)<<endl;
cout<<multiplies<int>()(3,5)<<endl;
cout<<divides<int>()(3,5)<<endl;
cout<<modulus<int>()(3,5)<<endl;
cout<<negate<int>()(3)<<endl;

4、关系运算类仿函数

  这类仿函数,提供基本的比较运算,示例如下:

//关系运算类仿函数
cout<<equal_to<int>()(3,5)<<endl;
cout<<not_equal_to<int>()(3,5)<<endl;
cout<<greater<int>()(3,5)<<endl;
cout<<greater_equal<int>()(3,5)<<endl;
cout<<less<int>()(3,5)<<endl;
cout<<less_equal<int>()(3,5)<<endl;

5、逻辑运算类仿函数

  这类仿函数,提供基本的逻辑运算,示例如下:

//逻辑运算类仿函数
cout<<logical_and<int>()(true, false)<<endl;
cout<<logical_or<int>()(true,false)<<endl;
cout<<logical_not<int>()(true)<<endl;

6、参数中转类仿函数

  这类仿函数,提供对输入参数不同的输出策略,示例如下:

//证同仿函数
cout<<identity<int>()(3)<<endl;

//选择仿函数
cout<<select1st<pair<int,int>>()(pair<int,int>(3,5))<<endl;
cout<<select2nd<pair<int,int>>()(pair<int,int>(3,5))<<endl;

//投射仿函数
cout<<project1st<int,int>()(3,5)<<endl;
cout<<project2nd<int,int>()(3,5)<<endl;

7、自定义仿函数

  使用STL的接口时,除了可以使用STL本身定义的仿函数以为,我们也可以定义自己的仿函数,以实现特定的需求。定义仿函数时,只用定义一个重载运算符()的类模板即可,示例如下:

template<class T>
struct display
{
    void operator()(const T& x) const 
    {
        cout<<x<<" ";
    }
};

int ia[] = {0,1,2,3,4,5,6,6,6,7,8};
vector<int> iv(ia,ia+sizeof(ia)/sizeof(int));
for_each(iv.begin(),iv.end(),display<int>());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值