map, hash_map, multimap的使用及区别

map对元素按照key按升序排序,比较的时候使用<操作符或者是程序员提供的比较函数。内置类型都定义了<操作符,可以直接作为key使用。自定义的类型如果要作为key,需要满足以下条件:

1. 可复制和可赋值(这是容器对元素的基本要求)

2. 元素类型定义了<操作符,或者定义一个专门的函数对象

struct _temp
{
int a, b;
  bool operator<(const struct _temp &rhs) const
  {
    return a < rhs.a;
  }
} ts;
...
map<struct _temp, int> my;

或者

struct _temp
{
    int a, b;        
} ts;
struct comparer{
    bool operator()(const struct _temp &a1, const struct _temp &a2)
    {
        return a1.a < a2.a;
    }
}
...
map<struct _temp, int, comparer> my;

hash_map(STL中叫unordered_map)使用一个hash函数计算key的hash值,并用另一个函数equal_to来判断两个key是否相等。如果要使用自定义类型作为key,需要定义哈希函数,==操作符或者一个函数对象比较。

struct _temp
{
    int a, b;
    bool operator==(const struct _temp &rhs) const
    {
        return a==rhs.a && b == rhs.b;
    }
} ts;

struct hashfun
{
    size_t operator()(const struct _temp &rhs) const
    {
        return rhs.a + rhs.b;
    }
};

unordered_map<struct _temp, int, hashfun> my;

multimap的使用与map类似,只是允许key相同。

map和multimap适合存储键有序的元素,hash_map适合存储键无序的元素。在内部实现上,map和multimap采用rb_tree。

 
posted @ 2012-09-12 22:00  segeon  阅读(1751)  评论(0)    收藏  举报