二十二,unordered_set和unordered_map的使用
1.unordered_set
1.1介紹
c++11
template<class Key,class Hash = std::hash<Key>,class KeyEqual = std::equal_to<Key>,class Allocator = std::allocator<Key>
> class unordered_set;
c++17
namespace pmr {template<class Key,class Hash = std::hash<Key>,class Pred = std::equal_to<Key>> using unordered_set = std::unordered_set<Key, Hash, Pred, std::pmr::polymorphic_allocator<Key>>;
}
- 定義在頭文件<unordered_set>
- Key就是unordered_set底層關鍵字的類型。
- unordered_set默認要求Key支持轉換為整形,如果不?持或者有額外的需求可以自行實現支持將Key轉成整形的仿函數傳給第?個模板參數。
- unordered_set默認要求Key支持比較相等,如果不?持或者想按??的需求?可以自行實現支持將Key比較相等的仿函數傳給第三個模板參數。
- unordered_set底層存儲數據的內存是從空間配置器申請的,如果需要可以自己實現內存池,傳給第四個參數。
- unordered_set底層是?哈希桶實現,增刪查平均效率是O(1),迭代器遍歷無序,為了跟set區分,所以取名unordered_set。
- 存儲元素和set一樣會去重。
1.2和set使用差異
? unordered_set的增刪查使用和set是一樣的。
差異:
- 對key的要求不同,set要求Key?持小于比較,?unordered_set要求Key?持轉成整形且?持等于?較。
- set是雙向迭代器,unordered_set是單向迭代器。
- set底層是紅黑樹,紅黑樹的底層是二叉搜索樹,所以中序遍歷是有序的,也就是實現了有序+去重;unordered_set底層是哈希表,遍歷時是無序的,無序+去重。
- 性能差異。紅?樹增刪查改效率是O(logN) ,?哈希表增刪查平均效率是O(1) 。
參考代碼:ANY_10/c_plus_plus - Gitee.com
2,unordered_multimap/unordered_multiset
unordered_multimap/unordered_multiset跟multimap/multiset功能完全類似,?持Key冗余。
unordered_multimap/unordered_multiset跟multimap/multiset的差異也是三個??的差異,key的要求的差異,iterator及遍歷順序的差異,性能的差異。
3,map和unordered_map
map和unordered_map與set和unoedered_set無太大差異。