仿函数--set/map常用
一 定义
仿函数 = 像函数用的对象,类实例
✅ 仿函数是一种类型
❌ 函数不是类型
二. 特点
- 像普通函数一样,可以有返回值,可以有参数
structmycompare{booloperator()(inta,intb)const{returna>b;// 降序}};仿函数可以重载多个 operator(),但一旦要放进 map,必须只有一个 bool operator()(T, T),并且是严格的比较逻辑。
- 可以作为参数进行传递(可以匿名形式,如greater(),)
map<int,int,mycompare>mp;- 可以具有状态
structCounter{intcount=0;voidoperator()(){++count;}};Counter c;c();c();c();// c.count == 3三 .应用
1️⃣ STL 算法(最常见)
std::vector v = {3,1,4};
// 从小到大
std::sort(v.begin(), v.end(), std::less());
// 从大到小
std::sort(v.begin(), v.end(), std::greater());
2️⃣ 自定义排序 / 比较规则
cpp
struct Person {
int age;
};
struct Older {
bool operator()(const Person& a, const Person& b) const {
return a.age > b.age;
}
};
std::sort(v.begin(), v.end(), Older{});
3️⃣ 带状态的仿函数(函数做不到)
✅ 算法过程中记录调用的次数
