C++ 中各种map的使用

2014-11-24 09:04:46 · 作者: · 浏览: 1

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


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


#include
#include
using namespace std;


typedef std::map Map;
typedef Map::iterator MapIt;


int main()
{
Map *map = new Map();
int key;
string value;
while(cin>>key>>value)
{
map->insert(make_pair(key, value));
}
for(MapIt it = map->begin(); it != map->end(); ++it)
cout<<"key:"<first<<" value:"<second< delete map;
return 0;
}


map使用红黑树实现。查找时间在O(lg(n))-O(2*log(n))之间,构建map花费的时间比较长,因而,map使用于那种插入和查询混合的情况。如果是先插入后查询的情况,可以考虑使用vector_map.


vector_map在C++中没有实现,想使用可以自己实现。其基本思想在于使用vector来保存数据,插入完成后进行排序,然后使用而分查找进行查询。这样在先插入后查询的条件下,性能会比map好很多。原因主要在一下几个方面。


map的key可以是自定义数据结构,但是需要重载<运算符。如下代码所示:


typedef struct _Key
{
_Key(int *p, int l)
{
len_ = l;
for(int i = 0; i < l; ++i)
p_[i] = p[i];
}
bool operator<(const _Key &rs) const
{
if(len_ == rs.len_)
{
for(int i = 0; i < len_; ++i)
return p_[i] < rs.p_[i];
return false;
}
else
return len_ < rs.len_;
}
int p_[MaxLen];
int len_;
}Key;
typedef std::map *> MyMap;