map有key和value
如果用map,默认是按key排序
用unordered_map则不排序
那么如何按照value进行排序呢:
一个很简单的做法就是用vector存map的key和value,因为sort方法只能对vector等进行排序,可以对sort施加约束:
#include<iostream>
#include<unordered_map>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
static bool cmp(pair<string,int>a,pair<string,int>b){
return a.second<b.second;//按value正序
//a.second>b.second为按value逆序
//a.first>b.frist为按key逆序
}
int main()
{
map<string,int>a;//或者 unordered_map<string,int>a;
a["bob"] = 97;
a["adam"] = 100;
a["john"] = 50;
cout << "map without sort:" << endl;
for(auto i=a.begin();i!=a.end();i++){
cout<<i->first<<": "<<i->second<<endl;
}
vector<pair<string,int>>b(a.begin(),a.end());
//等价于以下:
//for(auto i=a.begin(),i!=a.end();i++){
// b.push_back(pair<string,int>(i->first,i->second));
//}
sort(b.begin(),b.end(),cmp);
for(auto i=b.begin();i!=b.end();i++){
a[i->first] = i->second;//对原map进行修改需要加上这一行
// cout<<i->first<<": "<<i->second<<endl;
}
cout << "map with sorted: " << endl;
for(auto i=b.begin();i!=b.end();i++){
a[i->first] = i->second;
cout<<i->first<<": "<<i->second<<endl;
}
}
结果: