C++新特性探究(九):functor仿函数

相关博文:C++新特性探究(9.1):functor仿函数探究
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
仿函数技术难度不高,但对菜鸟来说侮辱性极强!

一. operator( )

  重载了operator()的类的对象,在使用中,语法类似于函数。故称其为仿函数
此种用法优于常见的函数回调。

例1:
在这里插入图片描述
附例1代码:

//小问学编程
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Compare
{
    
    
public:
    int operator()(int x,int y)
    {
    
    
        return x>y;
    }
};

int main()
{
    
    
    vector<int> myvec={
    
    1,3,5,7,9};
    sort(myvec.begin(),myvec.end(),Compare());

    for(auto& i:myvec)
        cout<<i<<endl;
}

二. 带状态的operator( )

  相对于函数,仿函数,可以拥有初始状态,一般通过class定义私有成员,并在声明对象的时候,进行初始化。

例2:
在这里插入图片描述
例3:
在这里插入图片描述
附例3代码:

//小问学编程
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Compare
{
    
    
public:
    Compare(bool f=true):flag(f){
    
    }
    int operator()(int x,int y)
    {
    
    
        if(flag)
            return x>y;
        else
            return x<y;
    }
protected:
    bool flag;
};

int main()
{
    
    
    vector<int> myvec={
    
    1,3,5,7,9};
    sort(myvec.begin(),myvec.end(),Compare(false));

    for(auto& i:myvec)
        cout<<i<<endl;
}

  私有成员的状态,就成了仿函数的初始状态。而由于声明一个仿函数对象可以拥有多个不同初始状态的实例。

例4:
在这里插入图片描述
附例4代码:

//小问学编程
#include<iostream>
using namespace std;

class Tax
{
    
    
public:
    Tax(float r,float b):_rate(r),_base(b){
    
    }
    float operator()(float money)
    {
    
    
        return(money-_base)*_rate;
    }
private:
    float _rate;
    float _base;
};

int main()
{
    
    
    Tax high(0.3,30000);
    Tax middle(0.2,15000);
    Tax low(0.1,3500);

    cout<<"请输入你的收入:";
    double salary;
    cin>>salary;
    if(salary>30000)
        cout<<high(salary)<<endl;
    else if(salary>15000)
        cout<<middle(salary)<<endl;
    else
        cout<<low(salary)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43297891/article/details/113523100