C++ STL中的map是以key排序的。
int main()
{
map<int, int> iMap;
iMap[1] = 20;
iMap[2] = 10;
iMap[5] = 30;
iMap[4] = 0;
for (auto it = iMap.begin(); it != iMap.end(); it++)
cout << it->first << ':' << it->second << '\n';
return 0;
}
那如果我要以value进行排序呢?
方案:将map的key和value以pair的形式装到vector中,对vector进行排序。
int main()
{
unordered_map<int, int> iMap;
iMap[1] = 20;
iMap[2] = 10;
iMap[5] = 30;
iMap[4] = 0;
vector<pair<int, int>> vtMap;
for (auto it = iMap.begin(); it != iMap.end(); it++)
vtMap.push_back(make_pair(it->first, it->second));
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;
}
注意:sort在外部定义
static bool cmp(pair<char, int> a , pair<char,int> b)
{
return a.second>b.second; //按照value从大到小重新排序
}
string frequencySort(string s) {
unordered_map<char,int> m;
for(auto i:s)
m[i]++;
vector<pair<char,int>> v;
for(auto i=m.begin();i!=m.end();i++)
{
v.push_back(pair<char,int>(i->first, i->second));
}
sort(v.begin(),v.end(),cmp);
return s;
}
把输入的字符串按照字母出现的频度排序 leetcode451
#include <stdio.h>
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>
#include<algorithm>
using namespace std;
int main(){
string str,res="";
cin>>str;
//cout<<str;
unordered_map<char,int>hashch;
vector<pair<char,int>>pahash;
for(int i=0;i<str.size();i++){
hashch[str[i]] ++;
}
for(auto it = hashch.begin();it !=hashch.end();it++){
pahash.push_back(make_pair(it->first,it->second));
}
sort(pahash.begin(),pahash.end(),[](const pair<char,int> &p1,const pair<char,int> &p2 ){
if (p1.second >p2.second)
return p1.second >p2.second ;
else if(p1.second ==p2.second )
return p1.first <p2.first;
return p1.second >p2.second ;
}
);
for(auto it =pahash.begin(); it != pahash.end();it++){
res +=string(it->second,it->first);
}
cout<<res<<endl;
return 0;
}
总结:c++中map unordered_map按照value排序
第一种做法是先建立一个vector<pair<type, type>>的容器。
std::vector<std::pair<int, int>> tmp;
for (auto& i : m)
tmp.push_back(i);
std::sort(tmp.begin(), tmp.end(),
[=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; });
第二种写法更加符合现代c++。首先建立一个临时map,然后通过transform函数将m中的元素inserter进tmp中。通过将map中元素的first和second交换达到,对value排序的目的。
std::map<int, int> tmp;
std::transform(m.begin(), m.end(), std::inserter(tmp, tmp.begin()),
[](std::pair<int, int> a) { return std::pair<int, int>(a.second, a.first); });
不过第二种写法要加头文件#include 和#include 。c++中的transform有点类似于python中的map
参考:https://blog.csdn.net/qq_17550379/article/details/80959968