STL:仿函数

1. 仿函数的基本用法

对于仿函数的使用需要:

  1. 创建一个类,类中要对 ( ) 运算符重载
  2. 创建函数,调用 ( ) 运算符重载,实现仿函数的使用
#include <iostream>
using namespace std;

void Func(int n){
   
        cout << "Hello World" << n << endl;
}

class Functor{
   
public:
        void operator () (int n){
   
                cout << __func__ << n << endl;
        }
};

int main(){
   
        Func(1);
        void (*pFunc)(int) = Func;   // 定义函数指针
        pFunc(2);

        // 仿函数,函数对象
        Functor func;      // 先定义一个对象
        func(3);     // 调用了()运算符重载
        func.operator()(4);
}

结果为:

Hello World1
Hello World2
operator()3
operator()4

2. 用于数组排序算法

2.1 sort 排序算法

对arr数组、vector容器内数据、list容器内数据排序
使用通用排序算法 sort

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;

// 控制降序
bool cmp(int a,int b){
   
        return a>b;
}

int main(){
   
        // arr数组排序
        int arr[] = {
   2,3,1,5,4,6};
        // sort(arr,arr+6);
        sort(begin(arr),end(arr),cmp);     // 不加cmp,默认升序
        for(auto n:arr){
   
                cout << n << " ";
        }
        cout << endl;

        // vector排序
        vector<int> c = {
   2,3,1,5,4,6};
        sort(c.begin(),c.end());
        for(auto n:c){
   
                cout << n << " ";
        }
        cout << endl;

        // list排序
        list<int> d = {
   2,3,1,5,4,6};
        d.sort();         // list有自己的排序方法sort
        for(auto n:d){
   
                cout << n << " ";
        }
        cout << endl;
}

结果为:

6 5 4 3 2 1 
1 2 3 4 5 6 
1 2 3 4 5 6

2.2 仿函数控制升降序

使用仿函数可以对数组的升降排序直接控制

#include <iostream>
#include <algorithm>
using namespace std;

// 控制降序
bool cmp(int a,int b){
   
        return a>b;
}

class Compare{
   
        bool asc;
public:
        Compare(bool asc):asc(asc){
   }    // 构造函数
        bool operator()(int a,int b)const{
        // ()运算符重载
                return asc?a<b:a>b;
        }
};

int main(){
   
        // 数组排序,使用仿函数
        int arr[] = {
   2,3,1,5,4,6};
        int a
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值