一 定义仿函数 像函数用的对象类实例✅ 仿函数是一种类型❌ 函数不是类型二. 特点像普通函数一样可以有返回值可以有参数structmycompare{booloperator()(inta,intb)const{returnab;// 降序}};仿函数可以重载多个 operator()但一旦要放进 map必须只有一个 bool operator()(T, T)并且是严格的比较逻辑。可以作为参数进行传递(可以匿名形式如greater(,)mapint,int,mycomparemp;可以具有状态structCounter{intcount0;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️⃣ 自定义排序 / 比较规则cppstruct 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️⃣ 带状态的仿函数函数做不到✅ 算法过程中记录调用的次数
仿函数--set/map常用
一 定义仿函数 像函数用的对象类实例✅ 仿函数是一种类型❌ 函数不是类型二. 特点像普通函数一样可以有返回值可以有参数structmycompare{booloperator()(inta,intb)const{returnab;// 降序}};仿函数可以重载多个 operator()但一旦要放进 map必须只有一个 bool operator()(T, T)并且是严格的比较逻辑。可以作为参数进行传递(可以匿名形式如greater(,)mapint,int,mycomparemp;可以具有状态structCounter{intcount0;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️⃣ 自定义排序 / 比较规则cppstruct 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️⃣ 带状态的仿函数函数做不到✅ 算法过程中记录调用的次数