目录

仿函数-greater-less

仿函数 greater less

仿函数

  • 仿函数是一个类或结构体,通过 重载 operator() 实现函数调用的效果。
  • 仿函数是一个对象,可以包含 成员变量 ,用于存储状态。
  • 仿函数可以结合 模板 使用,使其支持多种类型。
  • 仿函数通常是 内联 的(inline),性能可能比普通函数指针更高。

仿函数的使用

将仿函数作为参数传递

#include <iostream>
#include <vector>
#include <algorithm>

struct Printer {
    void operator()(int value) const {
        std::cout << value << " ";
    }
};

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

    // 使用仿函数 Printer 打印每个元素
    std::for_each(vec.begin(), vec.end(), Printer());  // 输出 1 2 3 4 5
    std::cout << std::endl;

    return 0;
}

在 std::sort 中使用仿函数

#include <iostream>
#include <vector>
#include <algorithm>

struct GreaterThan {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

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

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

    // 输出排序后的结果
    for (int num : vec) {
        std::cout << num << " ";  // 输出 4 3 2 1
    }
    std::cout << std::endl;

    return 0;
}

greater less

std::greaterstd::less
头文件<functional><functional>
std::sort 中的使用std::sort(vec.begin(), vec.end(), std::greater<int>()); // 降序排序std::sort(vec.begin(), vec.end(), std::less<int>()); // 升序排序
std::priority_queue 中的使用std::priority_queue<int, std::vector<int>, std::greater<int>> pq; // 小根堆std::priority_queue<int> pq; // 默认大根堆
与 Lambda 的关系[](int a, int b) { return a > b; }[](int a, int b) { return a < b; }