C++ 中各種map的使用

工程師WWW發表於2013-11-25

C++中有很多中key-value形式的容器,map/hash_map/unordered_map/vector_map。下面講述各個map的使用及其區別。

首先,map的基本使用方法如下:

  1. #include <iostream>  
  2. #include <map>  
  3. using namespace std;  
  4.   
  5. typedef std::map<int, string> Map;  
  6. typedef Map::iterator MapIt;  
  7.   
  8. int main()  
  9. {  
  10.     Map *map = new Map();  
  11.     int key;  
  12.     string value;  
  13.     while(cin>>key>>value)  
  14.     {  
  15.         map->insert(make_pair(key, value));  
  16.     }  
  17.     for(MapIt it = map->begin(); it != map->end(); ++it)  
  18.         cout<<"key:"<<it->first<<" value:"<<it->second<<endl;  
  19.     delete map;  
  20.     return 0;  
  21. }  

map使用紅黑樹實現。查詢時間在O(lg(n))-O(2*log(n))之間,構建map花費的時間比較長,因而,map使用於那種插入和查詢混合的情況。如果是先插入後查詢的情況,可以考慮使用vector_map.

vector_map在C++中沒有實現,想使用可以自己實現。其基本思想在於使用vector來儲存資料,插入完成後進行排序,然後使用而分查詢進行查詢。這樣在先插入後查詢的條件下,效能會比map好很多。原因主要在一下幾個方面。

  1. vector使用線性儲存,map是二叉樹形狀,所以vector的區域性性更好。
  2. vector可以一次分配很大的記憶體,而map需要每次分配一個節點,而且map中相對於vector有很多冗餘資料,比如指向子節點的指標。
  3. vector是插入完成後統一進行排序,而map每次insert都有一次查詢和樹的旋轉。
  4. vector_map是二分查詢,查詢時間穩定在O(lg(n)),而map的儲存結構是紅黑樹,查詢時間為O(lg(n))-O(2*log(n))。

map的key可以是自定義資料結構,但是需要過載<運算子。如下程式碼所示:

  1. typedef struct _Key  
  2. {  
  3.     _Key(int *p, int l)  
  4.     {  
  5.         len_ = l;  
  6.         for(int i = 0; i < l; ++i)  
  7.             p_[i] = p[i];  
  8.     }  
  9.     bool operator<(const _Key &rs) const  
  10.     {  
  11.         if(len_ == rs.len_)  
  12.         {  
  13.             for(int i = 0; i < len_; ++i)  
  14.                 return p_[i] < rs.p_[i];  
  15.             return false;  
  16.         }  
  17.         else  
  18.             return len_ < rs.len_;  
  19.     }  
  20.     int p_[MaxLen];  
  21.     int len_;  
  22. }Key;  
  23. typedef std::map<Key, vector<int> *> MyMap;  

需要注意的是,過載函式必須為const的。

當然,你也可以這麼做:

  1. typedef struct _Key  
  2. {  
  3.     _Key(int *p, int l)  
  4.     {  
  5.         len_ = l;  
  6.         for(int i = 0; i < l; ++i)  
  7.             p_[i] = p[i];  
  8.     }  
  9.     int p_[MaxLen];  
  10.     int len_;  
  11. }Key;  
  12. typedef struct _KeyCmp  
  13. {  
  14.     bool operator()(const Key &ls, const Key &rs)  
  15.     {  
  16.         if(ls.len_ == rs.len_)  
  17.         {  
  18.             for(int i = 0; i < ls.len_; ++i)  
  19.                 return ls.p_[i] < rs.p_[i];  
  20.             return false;  
  21.         }  
  22.         else  
  23.             return ls.len_ < rs.len_;  
  24.     }  
  25. }KeyCmp;  
  26. typedef std::map<Key, vector<int> *, KeyCmp> MyMap;  

與上面有相同的效果。

hash_map,STL中的實現叫做unordered_map,都是基於hash_table實現的。首先,分配一大片記憶體,形成很多桶。利用hash函式,將key對映到不同的桶中,當然,也有可能會有兩個不同的key對映到同一個桶中,這是,就需要判別函式來進行查詢了。所以,hash_map的key需要兩個條件,一個是hash函式,獲得對映到的桶的值,另外一個是equal_to函式,判定兩個key是否相等。顯然,當每個桶裡的元素個數比較平均且比較少的時候,查詢效能比較高。

使用樣例如下:

  1. #include <string>  
  2. #include <iostream>  
  3. #include <ext/hash_map>  
  4. using namespace std;  
  5. using namespace __gnu_cxx;  
  6.   
  7. struct str_hash  
  8. {  
  9.     size_t operator()(const string &s) const  
  10.     {  
  11.         return __stl_hash_string(s.c_str());  
  12.     }  
  13. };  
  14.   
  15. struct str_compare  
  16. {  
  17.     int operator()(const string &a, const string &b) const  
  18.     {  
  19.         return (a==b);  
  20.     }  
  21. };  
  22. typedef hash_map<string, string, str_hash, str_compare> StrMap;  
  23.   
  24. int main()  
  25. {  
  26.     StrMap strMap;  
  27.     string a,b;  
  28.     cout<<"插入:"<<endl;  
  29.     while(cin>>a>>b)  
  30.     {  
  31.         if(a.length() <= 1)  
  32.             break;  
  33.         strMap.insert(make_pair(a,b));  
  34.     }  
  35.     cout<<"查詢:"<<endl;  
  36.     while(cin>>a)  
  37.     {  
  38.         if(a.length() <= 1)  
  39.             break;  
  40.         if(strMap.find(a) != strMap.end())  
  41.             cout<<strMap[a]<<endl;  
  42.         else  
  43.             cout<<"not found"<<endl;  
  44.     }  
  45.     return 0;  
  46. }  

在編譯的時候會遇到warning:

  1. ***@ubuntu:~/Maps$ g++ -o hm hash_map.cpp   
  2. In file included from /usr/include/c++/4.6/ext/hash_map:61:0,  
  3.                  from hash_map.cpp:3:  
  4. /usr/include/c++/4.6/backward/backward_warning.h:33:2: 警告: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated. [-Wcpp]  

按照提示,g++編譯時新增引數即可消除。

unordered_map和hash_map的使用方式差不多,如下所示:

  1. #include <iostream>  
  2. #include <unordered_map>  
  3. #include <string>  
  4. using namespace std;  
  5.   
  6. unsigned int JSHash(const char *str)  
  7. {  
  8.     unsigned int hash = 1315423911;  
  9.     while(*str)  
  10.     {  
  11.         hash ^= ((hash<< 5) + (*str++) + (hash>>2));  
  12.     }  
  13.     return (hash & 0x7FFFFFFF);  
  14. }  
  15.   
  16. struct StrHash  
  17. {  
  18.     size_t operator()(const string &s) const  
  19.     {  
  20.         return JSHash(s.c_str());  
  21.     }  
  22. };  
  23. struct StrCompare  
  24. {  
  25.     bool operator()(const string &a, const string &b) const  
  26.     {  
  27.         return a==b;  
  28.     }  
  29. };  
  30. typedef unordered_map<string, string, StrHash, StrCompare> MyMap;  
  31. int main()  
  32. {  
  33.     MyMap mymap;  
  34.     string a,b;  
  35.     while(cin>>a>>b)  
  36.     {  
  37.         mymap[a] = b;  
  38.     }  
  39.     for(MyMap::iterator it = mymap.begin(); it != mymap.end(); ++it)  
  40.         cout<<it->first<<" "<<it->second<<endl;  
  41.     return 0;  
  42. }  

如果直接g++不帶其他引數編譯的話,會提示錯誤:

  1. ***@ubuntu:~/Maps$ g++ -o um unordered_map.cpp   
  2. In file included from /usr/include/c++/4.6/unordered_map:35:0,  
  3.                  from unordered_map.cpp:2:  
  4. /usr/include/c++/4.6/bits/c++0x_warning.h:32:2: 錯誤: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.  
  5. unordered_map.cpp:30:9: 錯誤: ‘unordered_map’不是一個型別名  
  6. unordered_map.cpp: 在函式‘int main()’中:  
  7. unordered_map.cpp:33:2: 錯誤: ‘MyMap’在此作用域中尚未宣告  
  8. unordered_map.cpp:33:8: 錯誤: expected ‘;’ before ‘mymap’  
  9. unordered_map.cpp:37:3: 錯誤: ‘mymap’在此作用域中尚未宣告  
  10. unordered_map.cpp:39:6: 錯誤: ‘MyMap’既不是類也不是名稱空間  
  11. unordered_map.cpp:39:22: 錯誤: expected ‘;’ before ‘it’  
  12. unordered_map.cpp:39:42: 錯誤: ‘it’在此作用域中尚未宣告  
  13. unordered_map.cpp:39:48: 錯誤: ‘mymap’在此作用域中尚未宣告  

需要在編譯時新增-std=c++0x引數即可。

總體來說,hash_map的查詢速度比map要快,因為hash_map的查詢速度與資料量大小無關,屬於常數級別。map的查詢速度是log(n)級別。但是hash_map每次查詢都需要執行hash函式,所以也比較耗時。而且,hash_map很多桶中可能都沒有元素,所以記憶體利用率不高。

所以,選擇map的時候,需要從三個方面考慮:應用場景/記憶體佔用/查詢速度

本次總結到此完畢,如有不詳盡之處或錯誤,請多多指教。


參考連結:

http://www.cnblogs.com/Frandy/archive/2011/07/26/Hash_map_Unordered_map.html

http://yujiawei.iteye.com/blog/409774

http://www.189works.com/article-7126-1.html

相關文章