C++(十三)— map的排序

  在c++中有两个关联容器,第一种是map,内部是按照key排序的,第二种是unordered_map,容器内部是无序的,使用hash组织内容的。

1、对有序map中的key排序

  如果在有序的map中,key是int,或者string,它们天然就能比较大小,本身的就是有序的。不用额外的操作。

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


struct CmpByKeyLength {
    bool operator()(const string& k1, const string& k2)const {
        return k1.length() < k2.length();
    }
};

int main()
{
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    // map<string, int> name_score_map;

    // 2、可以自定义,按照键值升序排列,注意加载 
    // #include <functional> // std::greater
    // map<string, int, greater<string>> name_score_map;

    //3、按照自定义内容进行排序,比如字符串的长度
    map<string, int, CmpByKeyLength> name_score_map;

    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    map<string, int>::iterator iter;
    for ( iter = name_score_map.begin();iter != name_score_map.end();++iter) {
        cout << (*iter).first << endl;
    }

    system("pause");
    return 0;
}

2、对有序map中的value排序

  把map中的元素放到序列容器(如vector)中,再用sort进行排序。

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


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

int main()
{
    //1、map这里指定less作为其默认比较函数(对象),就是默认按键值升序排列
    map<string, int> name_score_map;
    name_score_map["LiMin"] = 90;
    name_score_map["ZiLinMi"] = 79;
    name_score_map["BoB"] = 92;
    name_score_map.insert(make_pair("Bing", 99));
    name_score_map.insert(make_pair("Albert", 86));

    //输出添加的内容
    map<string, int>::iterator iter;
    for (iter = name_score_map.begin(); iter != name_score_map.end(); ++iter) {
        cout << (*iter).first << endl;
    }
    cout << endl;

    // 将map中的内容转存到vector中
    vector<pair<string, int>> vec(name_score_map.begin(), name_score_map.end());
    //对线性的vector进行排序
    sort(vec.begin(), vec.end(), cmp);
    for (int i = 0; i < vec.size(); ++i)
        cout << vec[i].first << endl;

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/eilearn/p/9473804.html