读书人

C++ 中各种地图的使用

发布时间: 2012-12-25 16:18:29 作者: rapoo

C++ 中各种map的使用

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

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

***@ubuntu:~/Maps$ g++ -o um unordered_map.cpp In file included from /usr/include/c++/4.6/unordered_map:35:0,                 from unordered_map.cpp:2:/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.unordered_map.cpp:30:9: 错误: ‘unordered_map’不是一个类型名unordered_map.cpp: 在函数‘int main()’中:unordered_map.cpp:33:2: 错误: ‘MyMap’在此作用域中尚未声明unordered_map.cpp:33:8: 错误: expected ‘;’ before ‘mymap’unordered_map.cpp:37:3: 错误: ‘mymap’在此作用域中尚未声明unordered_map.cpp:39:6: 错误: ‘MyMap’既不是类也不是命名空间unordered_map.cpp:39:22: 错误: expected ‘;’ before ‘it’unordered_map.cpp:39:42: 错误: ‘it’在此作用域中尚未声明unordered_map.cpp:39:48: 错误: ‘mymap’在此作用域中尚未声明

需要在编译时添加-std=c++0x参数即可。

总体来说,hash_map的查找速度比map要快,因为hash_map的查找速度与数据量大小无关,属于常数级别。map的查找速度是log(n)级别。但是hash_map每次查找都需要执行hash函数,所以也比较耗时。而且,hash_map很多桶中可能都没有元素,所以内存利用率不高。

所以,选择map的时候,需要从三个方面考虑:应用场景/内存占用/查找速度。

本次总结到此完毕,如有不详尽之处或错误,请多多指教。

读书人网 >C++

热点推荐