map按照value排序

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

// map按照value排序
// 按照单词出现个数排序
// 因为sort函数支持顺序容器,不支持关联容器的排序,所以要将map放进顺序容器里面

 int cmp(const pair<string,int> &PairIt1, const pair<string, int> &PairIt2)
{
    return PairIt1.second > PairIt2.second;
}
int main()
{
    map<string, int> map1;
    string str;
    cout << "输入单词:"<<endl;
    while (cin >> str)
    {
        pair<map<string,int>::iterator,bool> ret=  map1.insert(make_pair(str,1));
        if(!ret.second)  // 插入失败,表示有重复的值,所以map中的int要自增
        {
            ++ret.first->second;
        }
//        map1[str]++;   // 注意它和insert的差别
        if(cin.get() == '
')
            break;
    }

    // 将map存入vector中
    vector<pair<string,int> > vec;
    for(auto it = map1.begin(); it != map1.end(); it++)
    {
        vec.push_back(make_pair(it->first,it->second));
    }

    sort(vec.begin(),vec.end(), cmp);
    for(auto it = 0; it < vec.size(); it++)
    {
        cout << vec[it].first << " " << vec[it].second << endl;
    }


    return 0;
}

// 测试数据
// aa bb cc dd aa cc cc cc
//cc 4
//aa 2
//bb 1
//dd 1
 
原文地址:https://www.cnblogs.com/xiaokang01/p/12733557.html