仿函数

函数对象function objects,又名仿函数,一种行为类似函数的对象,调用者可以向函数一样使用该对象,其实现起来也比较简单:用户只需要实现一种新类型,在类中重载operator()即可,参数根据用户所要进行的操作选择匹配。如下所示:

class FunctionObjectType
 {  
public:  
  void operator() {  
       statements  

      }  
};

【例】使用仿函数实现一个冒泡排序

#include<iostream>
#include<stdlib.h>

using namespace std;

template<class T, class COM>
void BubbleSort(T* array, size_t len, COM compare)
{
    bool isBool = false;
    for (int i = 0; i < len; i++)
    {
        for (int j = 0; j < len - i - 1; j++)
        {
             if (compare(array[j], array[j + 1]))
             {
                 swap(array[j], array[j + 1]);
                 isBool = true;
             }
        }
        if (isBool == false)
        {
             return;
        }
    }
}
 
template<class T>
class Less
{
public:
    bool operator()(T& left, T& right)
    {
        return left < right;
    }
};
 
template<class T>
class Greater
{
public:
    bool operator()(T& left, T& right)
    {
        return left > right;
    }
};

int main()
{
    int array[] = { 2, 1, 4, 8, 9, 6, 5, 7, 3 };
    size_t len = sizeof(array) / sizeof(array[0]);
    cout << "原始数据为:";
    for (size_t i = 0; i < len; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;
    
    BubbleSort(array, len, Less<int>());
    cout << "递增排序后的数据为:";
    for (size_t i = 0; i < len; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;

    BubbleSort(array, len, Greater<int>());
    cout << "递减排序后的数据为:";
    for (int i = 0; i < len; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;

    system("pause");
    return 0;
}

运行结果为:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值