仿函数和谓词

本文详细介绍了C++中的仿函数,包括其定义、使用方式以及如何作为参数传递。通过示例展示了如何创建带有状态的仿函数,并将其用作谓词进行查找和排序操作。仿函数增强了函数的灵活性,可以拥有自己的状态并能够作为对象传递,为C++编程提供了更多可能性。

定义

仿函数创建的对象,也称为函数对象,两者是一个意思。
参考视频

  • 仿函数本质是个类,重载了小括号。
  • 仿函数可以作为参数传递。
  • 可以有自己的状态

使用

  • 普通使用
#include<bits/stdc++.h>
using namespace std;

class MyAdd{
public:
    int operator()(int a, int b){
        return a + b;
    }
};
int main(){
    MyAdd myAdd;
    cout<<myAdd(10, 5)<<endl;
    return 0;
}
  • 有自己的状态
#include<bits/stdc++.h>
using namespace std;

class MyAdd{
public:
    int count;
    int operator()(int a, int b){
        this->count ++;
        return a + b;
    }

    MyAdd(){
        this->count = 0;
    }
};
int main(){
    MyAdd myAdd;
    cout<<myAdd(10, 5)<<endl;
    cout<<myAdd(10, 5)<<endl;
    cout<<myAdd.count<<endl;
    return 0;
}
  • 作为参数传递
#include<bits/stdc++.h>
using namespace std;

class MyAdd{
public:
    int operator()(string world){
       cout<<"hello " + world<<endl;
    }
};

void doPrint(MyAdd &myAdd, string world){
    myAdd(world);
}
int main(){
    MyAdd myAdd;
    doPrint(myAdd, "C++");
    return 0;
}

谓词

返回bool类型的仿函数称为谓词

  • 如果operator()接受一个参数,称为一元谓词
  • 如果operator()接受两个参数,称为二元谓词

使用

  • 一元谓词
#include<bits/stdc++.h>
using namespace std;

class GreaterFive{
public:
    bool operator()(int val){
       return val > 5;
    }
};


int main(){
    vector<int> vt{1,2,3,4,5,6,7};
    //GreaterFive()称为匿名对象
    auto it = find_if(vt.begin(), vt.end(), GreaterFive());
    if(it != vt.end()) cout<<"找到大于5的数: "<<*it<<endl;
    else cout<<"未找到大于5的数"<<endl;
    return 0;
}
  • 二元谓词
#include<bits/stdc++.h>
using namespace std;

class MyCompare {
public:
    bool operator()(int a, int b) {
        return a > b;
    }
};

int main() {
    vector<int> vt{1, 312, 2, 5, 32, 77};
    sort(vt.begin(), vt.end(), MyCompare()); //从大到小的排序
    for(auto it: vt) cout<<it<<endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值