方法1 将pair存入vector排序
在map中存储 <key, value> 键值对的数据结构是pair,简单直接的想法是将map中的pair复制一份存储到vector中,并重写compare函数根据second元素排序,就可以使用sort对该vector进行排序。
代码实现
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
using namespace std;
// 重载比较函数
bool cmp(const pair<string, int> &a, const pair<string, int> &b)
{
return a.second < b.second;
}
// 对map进行排序
void sort_map_by_value(map<string, int> &m)
{
// 复制map中的pair到临时vector中
vector<pair<string, int>> tmpv(m.begin(), m.end());
// 使用STL的sort进行排序
sort(tmpv.begin(), tmpv.end(), cmp);
// 输出排序结果
for( auto &[x, y] : tmpv)
{
cout << x << ":" << y << endl;
}
}
int main()
{
map<string, int> M;
M = {
{"张三", 100},
{"小明", 67},
{"李子", 89},
{"二哈", 12},
{"独白", 75},
};
sort_map_by_value(M);
return 0;
}
输出:
二哈:12
小明:67
独白:75
李子:89
张三:100
方法2 使用multimap
什么是multimap
multimap是和map类似的关联容器,主要区别在于multimap中允许相同的key存在。
我们知道map的内部实现基于红黑树(一种平衡树),所以map中的key是自带排序,因此我们可以将待排序的map中的key和value互换,并插入到multimap中,即可实现排序
代码实现
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
using namespace std;
void sort_map_by_value_multimap(map<string, int> &m)
{
multimap<int, string> MM;
// 将m中的pair插入MM中
for(auto &t : m) MM.insert({t.second, t.first});
// 输出排序结果
for(auto &[x, y] : MM)
{
cout << y << ":" << x << endl;
}
}
int main()
{
map<string, int> M;
M = {
{"张三", 100},
{"小明", 67},
{"李子", 89},
{"二哈", 12},
{"独白", 75},
};
sort_map_by_value_multimap(M);
return 0;
}
输出
二哈:12
小明:67
独白:75
李子:89
张三:100