C++ STL map按value排序

(菜鸟的学习笔记,大佬们还是跳过吧)
放入map中的元素默认是按key排序的(用迭代器输出一遍就能发现)

按value进行排序,思路是先把map中的元素转存到vector,再用sort对vector进行排序

转存过程:

//map <string, int> M;
//vector <pair<string, int>> V;
//map <string, int>::iterator mit;
for (mit = M.begin(); mit != M.end(); mit++)
{
	V.push_back(make_pair(mit->first, mit->second));
}

完整代码如下:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

bool cmp(const pair<string, int> &a, const pair<string, int> &b)
{
    return a.second > b.second;
}

int main()
{
    map <string, int> M;
    vector <pair<string, int>> V;
    map <string, int>::iterator mit;
    vector <pair<string, int>>::iterator vit;
    string str;
    int n, num;
    while (~scanf("%d", &n))
    {
        for (int j = 0; j < n; j++)
        {
            cin >> str >> num;
            M[str] = num;
        }
        for (mit = M.begin(); mit != M.end(); mit++)
        {
            V.push_back(make_pair(mit->first, mit->second));
        }
        sort(V.begin(), V.end(), cmp);
        for (vit = V.begin(); vit != V.end(); vit++)
        {
            cout << vit->first << " " << vit->second << endl;
        }
//附上另一种迭代方式
//        for (auto vit: V)
//        {
//            cout << (&vit)->first << " " << (&vit)->second << endl;
//        }
        M.clear();
        V.clear();
    }

    return 0;
}

参考了众多大神们的博客,在此表示感谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值