• C++ functional库中的仿函数


    一、仿函数简介

    仿函数(functor)又称之为函数对象(function object),实际上就是 重载了()操作符 的 struct或class。
    由于重载了()操作符,所以使用他的时候就像在调用函数一样,于是就被称为“仿”函数啦。

    二、仿函数简要写法示例

    一个很正常的需求,定义一个仿函数作为一个数组的排序规则:
    将数组从大到小排序

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

    使用

    vector<int> a(10);
    iota(begin(a), end(a), 1);
    
    sort(begin(a), end(a), Cmp());  // 使用()
    
    for (auto x : a) {
      cout << x << " ";
    }
    

    输出
    10 9 8 7 6 5 4 3 2 1

    三、使用C++自带的仿函数

    在C++ 的functional头文件中,已经为我们提供好了一些仿函数,可以直接使用。

    (1)算术仿函数

    1.plus 计算两数之和
    例:将两个等长数组相加

        vector<int> a(10), b(a);
        iota(begin(a), end(a), 1);
        iota(begin(b), end(b), 1);
    
        transform(begin(a), end(a), begin(b), begin(a), plus<int>());
    
        for (auto x : a) {
            cout << x << " ";
        }
    

    输出
    2 4 6 8 10 12 14 16 18 20
    2.minus 两数相减
    将上面那个例子改一改:

    transform(begin(a), end(a), begin(b), begin(a), minus<int>());
    

    输出
    0 0 0 0 0 0 0 0 0 0

    3.multiplies 两数相乘
    再将上面那个例子改一改:

    transform(begin(a), end(a), begin(b), begin(a), multiplies<int>());
    

    输出
    1 4 9 16 25 36 49 64 81 100

    4.divides 两数相除
    还将上面那个例子改一改:

    transform(begin(a), end(a), begin(b), begin(a), divides<int>());
    

    输出
    1 1 1 1 1 1 1 1 1 1

    5.modules 取模运算
    继续将上面那个例子改一改:

    transform(begin(a), end(a), begin(b), begin(a), modulus<int>());
    

    输出
    0 0 0 0 0 0 0 0 0 0

    6.negate 相反数
    这次不能那样改了,因为上述的五个仿函数是二元仿函数,是对两个操作数而言的。
    negate是一元仿函数,只能对一个参数求相反数。
    所以我们对a数组求相反数:

    transform(begin(a), end(a), begin(a), negate<int>());
    

    输出
    -1 -2 -3 -4 -5 -6 -7 -8 -9 -10

    (2)关系仿函数

    1.equal_to 是否相等
    2.not_equal_to 是否不相等
    3.greater 大于
    4.less 小于
    5.greater_equal 大于等于
    6.less_equal 小于等于
    到这时,我们就可以看出,可以使用 greater() 来代替我们开头实现的例子
    将数组从大到小排序:

    vector<int> a(10);
    iota(begin(a), end(a), 1);
    
    sort(begin(a), end(a), greater<int>());  // 使用()
    
    for (auto x : a) {
      cout << x << " ";
    }
    

    输出
    10 9 8 7 6 5 4 3 2 1

    (3)逻辑仿函数

    1.logical_and 二元,求&
    2.logical_or 二元,求|
    3.logical_not 一元,求!

    使用方法同上.
    话说,并没有发现求异或的仿函数..

  • 相关阅读:
    机器学习笔记之隐马尔可夫模型(六)总结部分
    ANSYS二次开发:Python解析ansys fluent结果文件
    一文简要了解星闪技术优势点
    Puppeteer+RabbitMQ:Node.js 批量加工pdf服务架构设计与落地
    初识string+简单用法(二)
    C++ 网络编程学习五
    STM32个人笔记-CAN总线通讯
    vue3 项目部署,Nginx配置https,重定向,详细流程
    “永不断网”“多重热备份” | 美格智能5G链路聚合技术正式量产交付
    Arduino框架下ESP32/8266使用PROGMEM功能将数据存储到flash中的使用规范
  • 原文地址:https://www.cnblogs.com/Aatrowen-Blog/p/16112067.html