[C++]unordered_map的使用

unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。

不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素(key)是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。

所以使用时map的key需要定义operator<。而unordered_map需要定义hash_value函数并且重载operator==。但是很多系统内置的数据类型都自带这些,那么如果是自定义类型,那么就需要自己重载operator<或者 hash_value()了。

结论:如果需要内部元素自动排序,使用map,不需要排序使用unordered_map。

C++11为什么不把unordered_map定义为hash_map呢?那是因为在新标准出现之前很多库厂商已经暂用了hash_map这个名词。因此为了向前兼容不得不定义新的unordered_map。

所以unordered_map就是一个hash_table,类似一个用数组模拟的hash_table。但是要注意两个经常使用的函数:

find函数,在查找失败的时候返回map.end(),最后一个元素后面的一个仅仅起到标志作用的元素。

iterator find ( const key_type& k );
const_iterator find ( const key_type& k ) const;
Get iterator to element
Searches the container for an element with k as key and returns an iterator to it if found,
otherwise it returns an iterator to unordered_map::end (the element past the end of the container).

operator[]访问函数,这个可以根据key操作对应的value,跟数组模拟的hash_table使用一样。

mapped_type& operator[] ( const key_type& k );
mapped_type& operator[] ( key_type&& k );
Access element
If k matches the key of an element in the container, 
the function returns a reference to its mapped value.

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).

  

  

转载于:https://www.cnblogs.com/stemon/p/4819973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值