c++ STL map容器自定义排序规则
一、c++内置类型数据(int,float,double....)
#include// map容器 void test01() { map
//默认排序输出 for (map
int main() { test01(); return 0; } 运行结果:
默认通过key值从小到大排序
自定义排序规则通常是将升序改为降序
1.通过c++自定义的模板函数对象改变排序规则
声明时加入greater
例如上面的程序map改变声明为
map
输出结果变为
2.通过自定义函数对象改变排序规则
定义比较类如下,通过在类中重载operator()实现函数对象的功能
class Compare { public: bool operator()(int v1, int v2) { return v1 > v2; } };重新将声明改为
map
输出结果如下
二、自定义数据类型
#include
// map容器 class Student { public: int age; string name;
Student() {} Student(string name, int age) { this->name = name; this->age = age; } };
//年龄从大到小排,姓名从前往后排 class Comp { public: bool operator()(const Student &s1, const Student &s2) { if (s1.age == s2.age) return s1.name < s2.name; return s1.age > s2.age; } };
void test02() { map
int main() { test02(); return 0; }
输出结果:
....待续