unordered_map用法注意

C++ STL提供了 unordered_map,底层是用哈希表实现的,可以根据 key 搜索 对应的 value。

资料:http://www.cplusplus.com/reference/unordered_map/unordered_map/

 

1 template < class Key,                                    // unordered_map::key_type
2            class T,                                      // unordered_map::mapped_type
3            class Hash = hash<Key>,                       // unordered_map::hasher
4            class Pred = equal_to<Key>,                   // unordered_map::key_equal
5            class Alloc = allocator< pair<const Key,T> >  // unordered_map::allocator_type
6            > class unordered_map

第一点,一般来说,特化一个unordered_map只需要给出key 和 T, 后面的Hash, Pred和Alloc都可以用默认参数。但是如果要用自定义的数据结构作为key,就要提供对应的hash函数和比较函数。

第二点,是关于  operator[]  ,unordered_map重载了[],可以使用下标搜索值。

在介绍中有这么一段话:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

也就是说,如果用 operator[] 去搜索值,如果对应的key不存在,就会自动插入一个,对应的value会调用其默认构造函数。

所以说如果不确定某个key是否存在,要先用 unordered_map::find 去找,找到了再搜索对应值。不然就会在不经意间改变整个unordered_map。

 

posted @ 2018-07-17 09:44  Zzz...y  阅读(3291)  评论(0编辑  收藏  举报