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。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM