C++中如何按照map中的value来进行排序

时间:2023-03-09 18:01:34
C++中如何按照map中的value来进行排序

    sort函数无法对map进行排序,网上的方法一般是通过将map转为vector后,再来使用sort进行排序。

如下,

比较函数

bool cmp(const pair<int,int> & a,const pair<int,int> & b){
if(a.second!=b.second)
return a.second>b.second;
else
return a.first<b.first;
}

主函数

map<int,int> mps;
vector<pair<int,int> > ves(mps.begin(),mps.end());
sort(ves.begin(),ves.end(),cmp);

相关文章