項目進行中,使用到Map(std::map),Map要點整理以下:ios
1. Map,也叫關聯數組,提供key/value(鍵/值對),key用來索引,value是被存儲和檢索的數據。數組
2. key值惟一(Multimap除外)。數據結構
3. Map的內部數據結構是紅黑樹。app
3. 能夠用下標操做符,添加Map中的數據,例如map[1] = 2;,用下標操做符查找數據時,若是數據不存在,會被自動插入到Map中。less
4. Map中的數據默認按照由key從小到大排序(less),能夠修改第三個參數(可選)來修改排序法則。spa
程序舉例:code
1 // testMap.cpp : Defines the entry point for the console application. 2 // 3 4 #include "stdafx.h" 5 #include <string> 6 #include <map> 7 #include <iostream> 8 9 struct SortMap 10 { 11 bool operator ()( const int i1, const int i2 ) 12 { 13 return i1 > i2; 14 } 15 }; 16 17 //traverse the map 18 void traverseMap(const std::map<int, std::string>& map) 19 { 20 std::map<int, std::string>::const_iterator iter = map.begin(); 21 22 while(iter != map.end()) 23 { 24 std::cout << "" << iter->first << "," << iter->second << std::endl; 25 iter++; 26 } 27 } 28 29 void traverseSortMap(const std::map<int, std::string, SortMap>& map) 30 { 31 std::map<int, std::string, SortMap>::const_iterator iter = map.begin(); 32 33 while(iter != map.end()) 34 { 35 std::cout << "" << iter->first << "," << iter->second << std::endl; 36 iter++; 37 } 38 } 39 40 41 int _tmain(int argc, _TCHAR* argv[]) 42 { 43 std::map<int, std::string> map1; 44 map1[1] = "no"; 45 map1[6] = "hi"; 46 map1[5] = "me"; 47 map1[9] = "ok"; 48 49 traverseMap(map1); 50 std::cout << "-------------------------------------------" << std::endl; 51 52 std::map<int, std::string, SortMap> map2; 53 map2[1] = "no"; 54 map2[6] = "hi"; 55 map2[5] = "me"; 56 map2[9] = "ok"; 57 58 traverseSortMap(map2); 59 60 system("pause"); 61 return 0; 62 }
運行結果:blog
繼續努力~排序