C++ 中各种map的使用

来源:互联网 发布:snmp网络管理 编辑:程序博客网 时间:2024/06/10 07:40

C++中有很多中key-value形式的容器,map/hash_map/unordered_map/vector_map。下面讲述各个map的使用及其区别。

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

[cpp] view plaincopyprint?
  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可以是自定义数据结构,但是需要重载<运算符。如下代码所示:

[cpp] view plaincopyprint?
  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的。

当然,你也可以这么做:

[cpp] view plaincopyprint?
  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是否相等。显然,当每个桶里的元素个数比较平均且比较少的时候,查询性能比较高。

使用样例如下:

[cpp] view plaincopyprint?
  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:

[plain] view plaincopyprint?
  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的使用方式差不多,如下所示:

[cpp] view plaincopyprint?
  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++不带其他参数编译的话,会提示错误:

[plain] view plaincopyprint?
  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

原创粉丝点击