C++ map根据value进行排序以及根据key倒序

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

 结果:

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值