前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++中map按value排序

C++中map按value排序

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 11:21:02
10.6K0
发布2019-01-22 11:21:02
举报

我们知道C++ STL中的map是以key排序的。

代码语言:javascript
复制
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;
}

运行结果:

map运行结果
map运行结果

那如果我要以value进行排序呢? 方案:将map的key和value以pair的形式装到vector中,对vector进行排序。 (下面使用unordered_map,而没有使用map)

代码语言:javascript
复制
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;
}

运行结果:

unordered_map运行结果
unordered_map运行结果

这是从小大的排序结果,如果想要从大到小的排序,将sort函数中的第三个参数中Lambda表达式重点额函数体修改为:return y.second < x.second;即可!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年09月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档