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。

 

转载于:https://www.cnblogs.com/Zzz-y/p/9321689.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值