C++ Map按Value排序
源自今天的力扣练习前 K 个高频元素
,我用的不是最优方法,记录下该需求
map默认是按key值从小到大排序的
按value值排序想直接用sort排序是做不到的,sort只支持数组、vetctor等的排序,所以我们可以先把map装进pair里,然后再放入vector,自定义sort实现排序
下面是用lambda形式
int main()
{
unordered_map<int, int> iMap;
iMap[1] = 20;
iMap[2] = 10;
iMap[5] = 30;
iMap[4] = 0;
vector<pair<int, int>> vtMap(iMap.begin(), iMap.end());
sort(vtMap.begin(), vtMap.end(),
[](const pair<int, int> &x, const pair<int, int> &y) -> int {
return x.second < y.second;
});
for (auto it = vtMap.begin(); it != vtMap.end(); it++)
cout << it->first << ':' << it->second << '\n';
return 0;
}
也可以通过定义谓词函数实现
bool cmp(pair<char, int> a, pair<char, int> b)
{
return a.second < b.second; //按照value从大到小重新排序
}
int main()
{
unordered_map<int, int> iMap;
iMap[1] = 20;
iMap[2] = 10;
iMap[5] = 30;
iMap[4] = 0;
vector<pair<int, int>> vtMap(iMap.begin(), iMap.end());
/*sort(vtMap.begin(), vtMap.end(),
[](const pair<int, int>& x, const pair<int, int>& y) -> int {
return x.second < y.second;
});*/
sort(vtMap.begin(), vtMap.end(), cmp);
for (auto it = vtMap.begin(); it != vtMap.end(); it++)
cout << it->first << ':' << it->second << '\n';
return 0;
}
输出如下
4:0
2:10
1:20
5:30