爲了實現快速查找,map內部自己就是按序存儲的(好比紅黑樹)。在咱們插入<key, value>鍵值對時,就會按照key的大小順序進行存儲。Map的定義:算法
1 template < class Key, class T, class Compare = less<Key>, //入參爲key 2 //鍵 值 用於key比較的函數對象,與相對的greater 3 class Allocator = allocator<pair<const Key,T> > > 4 //用於存儲分配 5 class map;
其中less實現:less
1 template <class T> 2 struct less : binary_function <T,T,bool> 3 { 4 bool operator() (const T& x, const T& y) const 5 {return x<y;} 6 };
對Key排序dom
由上可知,按key排序,只需自定義一個用於比較的類就ok了。函數
例如:spa
1 struct CmpByKeyLength 2 { 3 bool operator()(const string& k1, const string& k2) 4 { 5 return k1.length() < k2.length(); 6 } 7 }; 8 int main() 9 { 10 map<string, int, CmpByKeyLength> name_score_map; 11 name_score_map["LiMin"] = 90; 12 name_score_map.insert(make_pair("Bing",99)); 13 name_score_map.insert(make_pair("Albert",86)); 14 for (map<string, int>::iterator iter = name_score_map.begin(); 15 iter != name_score_map.end(); 16 ++iter) 17 { 18 cout << *iter << endl; 19 } 20 21 return 0; 22 }
對Value排序code
對於value則既不能按Compare,也不能夠用sort,由於sort只可用於序列(線性)容器,而map是集合容器(例如:紅黑樹)對象
Map中的元素類型爲pairblog
1 template <class T1, class T2> struct pair 2 { 3 typedef T1 first_type; 4 typedef T2 second_type; 5 6 T1 first; //對應Key 7 T2 second; //對應Value 8 9 //構造函數 10 pair() : first(T1()), second(T2()) {} 11 pair(const T1& x, const T2& y) : first(x), second(y) {} 12 template <class U, class V> 13 pair (const pair<U,V> &p) : first(p.first), second(p.second) { } 14 }
此外,在<utility>頭文件中,還爲pair重載了 < 運算符排序
1 template<class _T1, class _T2> 2 inline bool operator < (const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) 3 { 4 return __x.first < __y.first || //key不一樣 5 (!(__y.first < __x.first) && __x.second < __y.second); //key相同,則比較value 6 //爲何不用==呢?由於做爲map的key必須實現<操做符的重載,至於==不能保證,並且浮點數… 7 }
因此用map + vector便可實現對value 的排序string
例如:
1 typedef pair< int, int> PAIR; 2 bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) { 3 return lhs.second < rhs.second; 4 } 5 struct CmpByValue { 6 bool operator()(const PAIR& lhs, const PAIR& rhs) { 7 return lhs.second < rhs.second; 8 } 9 }; 10 int main() { 11 map<int, int> myMap; 12 myMap [1] = 90; 13 myMap [2] = 79; 14 myMap.insert(make_pair(3,99)); 15 myMap insert(make_pair(4,86)); 16 //把map中元素轉存到vector中 17 vector<PAIR> name_score_vec(myMap.begin(), myMap.end()); 18 sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue()); 19 // sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value); 20 for (int i = 0; i != myMap.size(); ++i) { 21 cout << myMap [i] << endl; 22 } 23 return 0; 24 }
Sort算法以下:
1 template <class RandomAccessIterator> 2 void sort ( RandomAccessIterator first, RandomAccessIterator last ); 3 4 template <class RandomAccessIterator, class Compare> 5 void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );