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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM