C++ Primer 5th笔记(chap 11)关联容器---无序容器
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 11)关联容器---无序容器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
無序關聯容器 unordered associative container
?unordered_map
?unordered_set
?unordered_multimap
?unordered_multiset
1. 定義
- 一個hash函數和==運算符
- 無序容器在存儲上組織為一組桶,每個桶保存0到多個元素。
- 對于unordered_map或者unordered_set容器,其遍歷順序與創建該容器時輸入元素的順序是不一定一致的,遍歷是按照哈希表從前往后依次遍歷的
eg.
unordered_map<string, size_t> word_count; string word; while (cin >> word) {++word_count[word]; }for (auto e : word_count)cout << e.first;for(auto b = word_count.begin();b!= word_count.end();b++) {cout << b->first; }2. 無序容器管理操作
| 桶接口 | |
| c.bucket_count() | 正在使用的桶數目 |
| c.max_bucket_count() | 容器能容納的最多的桶的數量 |
| c.bucket_size(n) | 第n個桶中有多少個元素 |
| c.bucket(k) | 關鍵字為k的元素在哪個桶中 |
| 桶迭代 | |
| local_iterator | 可以用來訪問桶中元素的迭代器類型 |
| const_local_iterator | 桶迭代器的const版本 |
| c.begin(n), c.end(n) | 桶n的首元素迭代器和尾后迭代器 |
| c.cbegin(n), c.cend(n) | 與前兩個函數類似,但返回const_local_iterator |
| 哈希策略 | |
| c.load_factor() | 每個桶的平均元素數量,返回float值 |
| c.max_load_factor() | c試圖維護的平均桶大小,返回float值。c會在需要時添加新的桶,以使得load_factor<=max_load_factor |
| c.rehash(n) | 重組存儲,使得bucket_count>=n且bucket_count>size/max_load_factor |
| c.reserve(n) | 重組存儲,使得c可以保存n個元素且不必rehash |
3. 無序容器對關鍵字類型的要求
提供自己hash函數或==運算符
eg.
class Sales_data { public:int n;Sales_data() {}Sales_data(int) {}bool operator < (const Sales_data& lhs){return true;}bool static compareIsbn(const Sales_data& lhs, const Sales_data& rhs){return true;}std::string isbn() const { return ""; }// how to override default hash and equality operator on key_typesize_t static hasher(const Sales_data& sd){return hash<string>()(sd.isbn());}bool static eqOp(const Sales_data& lhs, const Sales_data& rhs){return lhs.isbn() == rhs.isbn();}// we'll see how to define our own operators in chapter 14bool operator =(const Sales_data& l){return l.n == this->n;} };typedef unordered_multiset<Sales_data, decltype(Sales_data::hasher)*, decltype(Sales_data::eqOp)*> SD_multiset;SD_multiset bookstore(42, Sales_data::hasher, Sales_data::eqOp);eg2.
// Foo must have == struct Foo { string s; };// we'll see how to define our own operators in chapter 14 bool operator==(const Foo& l, const Foo& r) { return l.s == r.s; } size_t FooHash(const Foo& f) { return hash<string>()(f.s); } unordered_set<Foo, decltype(FooHash)*> fooSet(10, FooHash);【引用】
https://github.com/thefistlei/cplusprimer/blob/main/cprimer/cprimer/mapTest.h
總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 11)关联容器---无序容器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha