參考:
https://www.jianshu.com/p/5b24ac2a6cac
在c++中有兩個關聯容器,第一種是map,內部是按照key排序的,第二種是unordered_map,容器內部是無序的,使用hash組織內容的。
1、對有序map中的key排序
如果在有序的map中,key是int,或者string,它們天然就能比較大小,本身的就是有序的。不用額外的操作。
爲了實現快速查找,map內部本身就是按序存儲的(比如紅黑樹)。在我們插入<key, value>鍵值對時,就會按照key的大小順序進行存儲,其中key的類型必須能夠進行 < 運算,且唯一,默認排序是按照從小到大便利記憶聯想到需要支持小於運算。
#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進行排序。
第一反應是利用stl中提供的sort算法實現,這個想法是好的,不幸的是,sort算法有個限制,利用sort算法只能對線性容器進行排序(如vector,list,deque)。map是一個集合容器,它裏面存儲的元素是pair,不是線性存儲的(前面提過,像紅黑樹),所以利用sort不能直接和map結合進行排序。
迂迴一下,把map中的元素放到序列容器(如vector)中,然後再對這些元素進行排序。要對序列容器中的元素進行排序,也有個必要條件:就是容器中的元素必須是可比較的,也就是實現了<操作的。
map是元素爲pair,其已實現<操作符的重載
#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;
}