C++学习随笔——C++仿函数的应用方法

仿函数的基本定义

仿函数(Functor),也称为函数对象(Function Object),是一个行为像函数的对象。实现仿函数的方法是重载类中的 operator() 操作符,使得对象能够像调用普通函数一样使用。仿函数的主要优势是它们可以拥有状态,并且可以被用于 STL 算法和容器中。

简单例子:

点击查看代码
#include <iostream>

class Adder {
public:
    // 重载 () 操作符
    int operator()(int a, int b) const {
        return a + b;
    }
};

int main() {
    Adder add; // 创建 Adder 对象
    int result = add(3, 4); // 像调用函数一样使用对象
    std::cout << "Result: " << result << std::endl; // 输出 Result: 7
    return 0;
}

用于 STL 算法:

点击查看代码
#include <iostream>
#include <vector>
#include <algorithm>

// 定义一个仿函数,用于判断两个整数的大小
class GreaterThan {
public:
    bool operator()(int a, int b) const {
        return a > b;
    }
};

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5, 9};

    // 使用仿函数 GreaterThan 对 vector 进行降序排序
    std::sort(vec.begin(), vec.end(), GreaterThan());

    // 输出排序后的 vector
    for (int n : vec) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // 输出: 9 5 4 3 1 1

    return 0;
}

保持状态的仿函数:

点击查看代码
#include <iostream>
#include <vector>
#include <algorithm>

// 定义一个仿函数,用于计算累计和
class Accumulator {
private:
    int total;
public:
    Accumulator() : total(0) {}

    void operator()(int n) {
        total += n;
    }

    int getTotal() const {
        return total;
    }
};

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    Accumulator acc = std::for_each(vec.begin(), vec.end(), Accumulator());

    std::cout << "Total sum: " << acc.getTotal() << std::endl; // 输出: Total sum: 15

    return 0;
}

参数化的行为:

点击查看代码
#include <iostream>

class Multiply {
private:
    int factor;
public:
    // 构造函数
    Multiply(int f) : factor(f) {}

    // 重载 () 操作符
    int operator()(int x) const {
        return x * factor;
    }
};

int main() {
    Multiply timesTwo(2); // 创建一个乘以2的仿函数
    Multiply timesThree(3); // 创建一个乘以3的仿函数

    std::cout << "2 * 4 = " << timesTwo(4) << std::endl; // 输出 2 * 4 = 8
    std::cout << "3 * 4 = " << timesThree(4) << std::endl; // 输出 3 * 4 = 12

    return 0;
}

posted @   北宸于烁  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示