目录
为什么选择deque作为stack和queue的底层默认容器
一、仿函数
仿函数(Functor):也称为函数对象(Function Object),是一种在 C++ 中通过类或结构体实现的可调用实体。
仿函数的核心特点是 重载了 operator() 运算符,使得类的对象可以像普通函数一样被调用。
仿函数是 C++ 中 “以类模拟函数” 的重要机制,这种机制结合了面向对象的封装性和函数的灵活性,在 STL和算法中有着广泛应用。
仿函数的核心特点:
1. 重载 operator()
通过在类中定义 operator() 运算符,使得该类的对象可以像函数一样被调用:
class Adder {
public:
int operator()(int a, int b) {
return a + b;
}
};
int main() {
Adder add; // 创建仿函数对象
int sum = add(3,5); // 像函数一样调用
// sum = 8
}
仿函数的优势
1.状态保持:仿函数可以像普通类一样拥有成员变量,用于存储状态或参数,这使得它比普通函数更灵活。
2.模板兼容性:仿函数可以作为模板参数传递,提供更大的灵活性
3.内联优化:编译器更容易对仿函数进行内联优化
4.多态性:可通过继承实现更复杂的行为
仿函数的用途
1. STL算法中的比较器和谓词
- 比较器:通过仿函数指定排序规则(如:升序 / 降序)
#include <algorithm> #include <vector> using namespace std; class Greater { public: bool operator()(int a, int b) const // 降序比较 { return a > b; } }; int main() { vector<int> nums = {3, 1, 4, 2}; sort(nums.begin(), nums.end(), Greater()); // 使用仿函数指定降序 // 排序结果:4 3 2 1 return 0; }谓词:用于筛选元素
class IsEven { public: bool operator()(int x) const { return x % 2 == 0; // 判断是否为偶数 } }; vector<int>::iterator it = find_if(nums.begin(), nums.end(), IsEven());
2. 自定义算法逻辑
- 在自定义算法中,通过仿函数将逻辑抽象出来,提高代码复用性
template<class Compare> void BubbleSort(int* a, int n,

最低0.47元/天 解锁文章
2230

被折叠的 条评论
为什么被折叠?



