仿函数
- 仿函数是一个类或结构体,通过重载 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 5std::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::greater | std::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; } |