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);

 

posted @ 2018-02-25 22:02  张杨  阅读(570)  评论(0编辑  收藏  举报