C++中map对value排序的思路
因为在日常使用中我们经常遇到类似于 姓名/分数 的存储类型
这个时候常常要对分数进行排序
对于map,默认是对key排序,因此就产生了这个问题
关于这个问题,我第一个想到的是利用algorithm中的sort来进行排序
其中map中的元素为pair,因此我会想到为sort编写cmp函数从而对自定义类型比较
#include "unordered_map"
#include "algorithm"
unordered_map <string, int> students; //姓名,分数
bool cmp(pair <string, int> a, pair <string, int> b){
return a.second > b.second; //分数从高到低
}
sort(students.begin(), students.end(), cmp);
但是很可惜,sort只能对线性容器进行排序,而students本质上是一个散列表
尽管map中也有自定义排序,但写法过于复杂
所以有一个简单的思路,就是在排序的时候将map转化为vector
#include "unordered_map"
#include "algorithm"
#include "vector"
unordered_map <string, int> students; //姓名,分数
vector <string, int> tmp_students; //临时存放
bool cmp(pair <string, int> a, pair <string, int> b){
return a.second > b.second; //分数从高到低
}
void sort_map(unordered_map <string, int>& students){ //挂上引用操作原来的map
//先清理数组,防止残留
tmp_students.clear();
//将map中的元素放到vector中
for (auto a : students){
tmp_students.push_back(a);
}
//对vector排序
sort(students.begin(), students.end(), cmp); //其实这里已经可以后续操作了,但还是放回map中
students.clear(); //清理之后再放入
for (auto a : tmp_students){
map[a.first] = a.second;
}
}
sort_map(students);
这样就实了简单的map对value排序