c++ STL map容器自定义排序规则


一、c++内置类型数据(int,float,double....)

#include using namespace std;
// map容器 void test01() {     map m;     // map的几种初始化操作     m.insert(make_pair(5, "hhh"));     m.insert(pair(3, "lll"));     m.emplace(4, "ggg");     m[1] = "abc";
    //默认排序输出     for (map::iterator it = m.begin(); it != m.end(); ++it)     {         cout << "key:" << it->first << " value:" << it->second << endl;     } }
int main() {     test01();     return 0; } 运行结果:

默认通过key值从小到大排序 

自定义排序规则通常是将升序改为降序

1.通过c++自定义的模板函数对象改变排序规则

声明时加入greater,使用时应加入头文件,或者使用万能头文件

例如上面的程序map改变声明为

map>m;

输出结果变为

 2.通过自定义函数对象改变排序规则

定义比较类如下,通过在类中重载operator()实现函数对象的功能

class Compare { public:     bool operator()(int v1, int v2)     {         return v1 > v2;     } };

重新将声明改为

mapm;

输出结果如下

二、自定义数据类型


#include using namespace std;
// 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 m;     m.insert(make_pair(Student("aaa", 19), "班长"));     m.insert(make_pair(Student("bbb", 19), "学习委员"));     m.insert(make_pair(Student("ccc", 20), "团支书"));     m.insert(make_pair(Student("ddd", 35), "老师"));     //输出     for (auto it = m.begin(); it != m.end(); ++it)     {         cout << "姓名:" << it->first.name << " 年龄:" << it->first.age << " 职务:" << it->second << endl;     } }
int main() {     test02();     return 0; }

输出结果:

....待续

相关