參考:http://www.cplusplus.com/reference/unordered_map/unordered_map/?kw=unordered_map
std::unordered_map(C++11)
template < class Key, // unordered_map::key_type class T, // unordered_map::mapped_type class Hash = hash<Key>, // unordered_map::hasher class Pred = equal_to<Key>, // unordered_map::key_equal class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type > class unordered_map;
無序的映射
無序映射是存儲鍵值和映射值組合形成的元素的關聯容器,它允許根據鍵快速檢索單個元素。
在unordered_map中,鍵值通常用於惟一地標識元素,而映射的值是一個對象,其內容與此鍵相關聯。鍵和映射值的類型可能不同。
在內部,unordered_map中的元素沒有對鍵值或映射值以任何特定的順序排序,但組織成buckets的形式都取決於他們的散列值,以便通過它的鍵值快速訪問單個元素(平均一個恆定的平均時間復雜度)。
unordered_map容器比map容器能更快地通過它們的鍵訪問單個元素,盡管它們通常對於元素子集的范圍迭代效率較低。
無序映射實現了直接訪問操作符(operator[]),該操作符允許使用其鍵值作為參數直接訪問映射值。
容器中的迭代器至少是前向迭代器forward iterators。
Container properties容器屬性
- Associative關聯性
- 關聯容器中的元素由它們的鍵引用,而不是由它們在容器中的絕對位置引用。
- Unordered無序性
無序容器使用散列表來組織它們的元素,散列表允許通過它們的鍵快速訪問元素。
- Map映射
每個元素都將一個鍵關聯到一個映射值:鍵表示標識其主要內容為映射值的元素。
- Unique keys
- 容器中的任何兩個元素都不能具有相同的鍵。
- Allocator-aware
容器使用一個分配器對象來動態地處理它的存儲需求。
Template parameters模版參數
key:
鍵值的類型。unordered_map中的每個元素都由其鍵值唯一標識。
別名為成員類型unordered_map::key_type。
T:
映射值的類型。unordered_map中的每個元素都用於將一些數據存儲為其映射值。
別名為成員類型unordered_map::mapped_type。注意,這與unordered_map::value_type(參見下面)不同。
- Hash:
-
一個一元函數對象類型,它接受一個key類型的對象作為參數,並基於它返回一個類型size_t的唯一值。它可以是實現函數調用操作符的類,也可以是指向函數的指針(參見構造函數的示例)。默認值是hash<key>,它返回一個散列值,碰撞概率接近1.0/std::numeric_limits<size_t>::max()。
unordered_map對象使用此函數返回的散列值在內部組織其元素,從而加快了定位單個元素的過程。
別名為成員類型unordered_map::hasher。
- Pred:( 判斷兩個鍵值是否相同)
-
一個二進制謂詞,它接受兩個鍵key類型的參數並返回一個bool。表達式pred (a, b), pred是這種類型的一個對象,a和b是鍵值,如果a應考慮相當於b則返回true。這可以是一個實現一個函數調用操作符或指向函數的指針(見構造函數為例)的類。這默認為equal_to<key>,它返回的結果與應用equal-to操作符相同(a==b)。
unordered_map對象使用這個表達式來確定兩個元素鍵是否相等。使用此謂詞,unordered_map容器中的任何兩個元素都不能具有產生true的鍵。
別名為成員類型unordered_map::key_equal。
- Alloc:
-
用於定義存儲分配模型的分配器對象的類型。默認情況下,使用的是分配器類模板,它定義了最簡單的內存分配模型,並且是與值無關的。
別名為成員類型unordered_map::allocator_type。 -
在unordered_map成員函數的引用中,模板參數使用相同的名稱(Key、T、Hash、Pred和Alloc)。
unordered_map容器元素的迭代器同時訪問鍵和映射值。為此,該類定義了一個名為value_type的類,它是一個pair類,它的第一個值對應於鍵類型的const版本(模板參數鍵),第二個值對應於映射的值(模板參數T):
typedef pair<const Key, T> value_type;
unordered_map容器的迭代器指向此value_type的元素。因此,對於一個指向map元素的迭代器來說,它的鍵和映射值可以分別通過以下方式訪問:
unordered_map<Key,T>::iterator it; (*it).first; // the key value (of type Key) (*it).second; // the mapped value (of type T) (*it); // the "element value" (of type pair<const Key,T>)
當然,任何其他直接訪問操作符,如->或[]都可以使用,例如:
it->first; // same as (*it).first (the key value) it->second; // same as (*it).second (the mapped value)
Member types成員類型
以下別名是unordered_map的成員類型。它們被成員函數廣泛用作參數和返回類型:
| 成員類型 | 定義 | notes |
| key_type | 第一個模版參數(Key) | |
| mapped_type | 第二個模版參數(T) | |
| value_type | pair<const key_type,mapped_type> | |
| hasher | 第三個模版參數(Hash) | 默認為:hash<key_type> |
| key_equal | 第四個模版參數(Pred) | 默認為:equal_to<key_type> |
| allocator_type | 第五個模版參數(Alloc) | 默認為:allocator<value_type> |
| reference | Alloc::reference | |
| const_reference | Alloc::const_reference | |
| pointer | Alloc::pointer | 默認為allocator: value_type* |
| const_pointer | Alloc::const_pointer | 默認為allocator: const value_type* |
| iterator | value_type的前向迭代器 | |
| const_iterator | const value_type的前向迭代器 | |
| local_iterator | value_type的前向迭代器 | |
| const_local_iterator | const value_type的前向迭代器 | |
| size_type | 一個無符號的整數類型 | 等同於size_t |
| difference_type | 一個有符號的整數類型 | 等同於ptrdiff_t |
Member functions成員函數
1)構造函數
empty (1) explicit unordered_map ( size_type n = /* see below */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& alloc = allocator_type() ); explicit unordered_map ( const allocator_type& alloc );
range (2) template <class InputIterator> unordered_map ( InputIterator first, InputIterator last, size_type n = /* see below */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& alloc = allocator_type() );
copy (3) unordered_map ( const unordered_map& ump ); unordered_map ( const unordered_map& ump, const allocator_type& alloc );
move (4) unordered_map ( unordered_map&& ump ); unordered_map ( unordered_map&& ump, const allocator_type& alloc );
initializer list (5) unordered_map ( initializer_list<value_type> il, size_type n = /* see below */, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& alloc = allocator_type() );
構建unordered_map
構造一個unordered_map容器對象,根據使用的構造函數版本初始化其內容:
(1)空容器構造函數(默認構造函數)
構造一個空的unordered_map對象,該對象不包含元素,大小為0。
它可以使用特定的hasher、key_equal和分配器對象以及最少數量的散列桶來構造容器。
(2)range構造函數
構造一個unordered_map對象,該對象包含[first,last)范圍內每個元素的副本。
(3)復制構造函數(以及復制分配器)
對象初始化為具有與unordered_map對象ump相同的內容和屬性。
(4)移動構造函數(以及使用分配器移動)
對象獲取rvalue右值ump的內容。
(5)初始化器列表
用列表的內容初始化容器。
參數:
n:
初始桶的最小數量。
這不是容器中的元素數量,而是構造內部哈希表所需的最小槽數。
如果沒有指定這個參數,構造函數將自動確定(以一種依賴於特定庫實現的方式)。
成員類型size_type是無符號整數類型。
hf:
hasher函數對象。hasher是一個基於作為參數傳遞給它的容器對象鍵值key而返回整數值的函數,即該整數值 = hasher(key)。
成員類型hasher在unordered_map中定義為其第三個模板參數(Hash)的別名。
eql:
如果作為參數傳遞的兩個容器對象鍵key被認為是相等的,則返回true。
成員類型key_equal在unordered_map中定義為其第四個模板參數(Pred)的別名。
alloc:
要使用的分配器對象,而不是構造新對象。
對於使用默認分配器類模板版本的類實例化,此參數不相關。
成員類型allocator_type在unordered_map中定義為其第五個模板參數(Alloc)的別名。
- first, last:
-
將迭代器輸入到范圍的初始和最終位置。使用的范圍是[first,last),它包括first和last之間的所有元素,包括first指向的元素,但不包括last指向的元素。
函數模板類型可以是任何類型的輸入迭代器。
- ump:
- 另一個相同類型的unordered_map對象(具有相同的類模板參數),其內容可以復制或移動。
- il:
-
一個initializer_list對象。
這些對象是由初始化器列表聲明器自動構造的。
成員類型value_type是容器中元素的類型,在unordered_map中定義為pair<const key_type,mapped_type>,其中成員類型key_type是第一個模板參數(key類型)的別名,而mapped_type是第二個模板參數(映射mapped類型,T)的別名。 - 舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; using stringmap = unordered_map<string, string>; stringmap merge(stringmap a, stringmap b){ stringmap temp{a}; temp.insert(b.begin(), b.end()); return temp; } int main(){ stringmap first; stringmap second {{"apple", "red"},{"lemon","yellow"}}; stringmap third {{"orange","orange"}, {"strawberry", "red"}}; stringmap fourth (second); stringmap fifth (merge(third, fourth)); stringmap sixth (fifth.begin(), fifth.end()); cout << "sixth contains : "; for(auto& x:sixth) cout << " " << x.first << ":" << x.second; cout << endl; return 0; }
返回:
sixth contains : orange:orange strawberry:red lemon:yellow apple:red
2)析構函數
~unordered_map();
銷毀無序的映射
銷毀容器對象。這將調用所包含元素的每個析構函數,並釋放由unordered_map容器分配的所有存儲容量。
3)賦值操作
copy (1) unordered_map& operator= ( const unordered_map& ump );
move (2) unordered_map& operator= ( unordered_map&& ump );
initializer list (3) unordered_map& operator= ( intitializer_list<value_type> il );
賦值內容
賦值ump(或il)作為容器的新內容。
在調用之前包含在對象中的元素被銷毀,並被unordered_map ump或初始化器列表il中的元素替換(如果有的話)。
第一個版本(1)執行一個復制賦值,它將ump的所有元素復制到容器對象中(ump保留其內容)。
第二個版本(2)執行移動分配,將ump內容的所有權轉移給對象。沒有賦值發生:內容被ump丟棄。
第三個版本(3)將初始化器列表il的內容賦值為容器對象的元素。
參數:
- ump:
- 有着相同類型的unordered_map對象(有着相同的模版參數)
- il:
-
一個initializer_list對象。編譯器將從初始化器列表聲明器自動構造這些對象。
成員類型value_type是unordered_map中包含的元素的類型,它是pair<const key_type,mapped_type>,其中成員類型key_type是第一個模板參數(key類型)的別名,而mapped_type是第二個模板參數(mapped映射類型,T)的別名。 - 返回值:
- *this
- 舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; using stringmap = unordered_map<string, string>; stringmap merge(stringmap a, stringmap b){ stringmap temp{a}; temp.insert(b.begin(), b.end()); return temp; } int main(){ stringmap first, second, third; first = {{"AAPL","Apple"},{"MSFT","Microsoft"}}; //初始化列表 second = {{"GOOG", "Google"}, {"ORCL", "Oracle"}}; third = merge(first, second); first = third; cout << "first contains : "; for(auto& x:first) cout << " " << x.first << ":" << x.second; cout << endl; return 0; }
返回:
first contains : GOOG:Google ORCL:Oracle MSFT:Microsoft AAPL:Apple
Capacity容量
4)empty
bool empty() const noexcept;
測試容器是否為空
返回一個bool值,該值指示unordered_map容器是否為空,即其大小是否為0。
此函數不以任何方式修改容器的內容。要清除數組對象的內容,成員函數unordered_map::clear是存在的。
參數:
none
返回值:
如果容器大小為0則返回true,否則返回false
舉例:
#include <iostream> #include <unordered_map> using namespace std; int main(){ unordered_map<int, int> first; unordered_map<int, int> second = {{1,10},{2,20},{3,30}}; cout << "first " << (first.empty()?"is empty":"is not empty") << endl; cout << "second " << (second.empty()? "is empty" : "is not empty") << endl; return 0; }
返回:
first is empty second is not empty
5)size
size_type size() const noexcept;
返回容器大小
返回unordered_map容器中的元素數量。
參數:
none
返回值:
容器中元素的數量。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,double> mymap ={ {"milk", 2.30}, {"potatoes", 1.90}, {"eggs", 0.40} }; cout << "mymap.size() is " << mymap.size() << endl; return 0; }
返回:
mymap.size() is 3
6)max_size
size_type max_size() const noexcept;
返回最大大小
返回unordered_map容器可以容納的元素的最大數量。
這是由於系統約束或其庫實現的限制,容器所能容納的最大潛在元素數。
參數:
none
返回值:
對象可以作為內容容納的元素的最大數目。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <unordered_map> using namespace std; int main(){ unordered_map<int,int> mymap; cout << "max_size = " << mymap.max_size() << endl; cout << "max_bucket_count = " << mymap.max_bucket_count() << endl; cout << "max_load_factor = " << mymap.max_load_factor() << endl; return 0; }
返回:
max_size = 768614336404564650 max_bucket_count = 768614336404564650 max_load_factor = 1
Iterators迭代器
7)begin
container iterator (1) iterator begin() noexcept; const_iterator begin() const noexcept;
bucket iterator (2) local_iterator begin ( size_type n ); const_local_iterator begin ( size_type n ) const;
返回迭代器開始
返回一個迭代器,該迭代器指向unordered_map容器(1)或其中一個桶(2)中的第一個元素。
注意,unordered_map對象不能保證哪個特定的元素被認為是它的第一個元素。但是,在任何情況下,從開始到結束的范圍覆蓋容器(或桶)中的所有元素,直到失效。
參數:
n:
桶數。這應該小於bucket_count。
它是一個可選參數,可以改變這個成員函數的行為:如果設置,迭代器將檢索到該桶的第一個元素,否則它將指向容器的第一個元素。
成員類型size_type是無符號整數類型。
返回值:
容器(1)或桶(2)中的第一個元素的迭代器。
所有返回類型(iterator、const_iterator、local_iterator和const_local_iterator)都是成員類型。在unordered_map類模板中,這些是正向迭代器類型。
局部迭代器與非局部迭代器屬於同一類別。它們的value_type、diffence_type、指針和引用成員類型也是相同的。但是迭代器本身不一定是相同類型的。
8)end
container iterator (1) iterator end() noexcept; const_iterator end() const noexcept;
bucket iterator (2) local_iterator end (size_type n); const_local_iterator end (size_type n) const;
返回迭代器終點
返回一個迭代器,該迭代器指向unordered_map容器(1)或其中一個桶(2)中的past-the-end元素。
end返回的迭代器不指向任何元素,而是指向unordered_map容器中最后一個元素后面的位置(它的結束位置)。因此,返回的值不能取消引用——它通常用於描述一個范圍的開放端,比如[begin,end]。
注意,unordered_map對象並不保證其元素的順序。但是,在任何情況下,從開始到結束的范圍覆蓋容器(或桶)中的所有元素,直到失效。
參數:
n:
桶數。這應該小於bucket_count。
它是一個可選參數,可以改變這個成員函數的行為:如果設置,迭代器將檢索到該桶的第一個元素,否則它將指向容器的第一個元素。
成員類型size_type是無符號整數類型。
返回值:
元素的迭代器,遍歷容器(1)或桶(2)的末端。
所有返回類型(iterator、const_iterator、local_iterator和const_local_iterator)都是成員類型。在unordered_map類模板中,這些是正向迭代器類型。
局部迭代器與非局部迭代器屬於同一類別。它們的value_type、diffence_type、指針和引用成員類型也是相同的。但是迭代器本身不一定是相同類型的。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, string> mymap; mymap = {{"Australia", "canberra"}, {"U.S.", "Washington"}, {"France", "Paris"}}; cout << "mymap contains : "; for(auto it = mymap.begin(); it!=mymap.end(); ++it) cout << " " << it->first << " : " << it->second; cout << endl; cout << "mymap's buckets contains: \n"; for(unsigned i = 0; i<mymap.bucket_count(); ++i){ cout << "bucket #" << i << " contains : "; for(auto local_it = mymap.begin(i); local_it!=mymap.end(i); ++local_it) cout << " " <<local_it->first << " : " << local_it->second; cout << endl; } return 0; }
返回:
mymap contains : France : Paris U.S. : Washington Australia : canberra mymap's buckets contains: bucket #0 contains : bucket #1 contains : bucket #2 contains : France : Paris bucket #3 contains : U.S. : Washington Australia : canberra bucket #4 contains :
9)cbegin
container iterator (1) const_iterator cbegin() const noexcept;
bucket iterator (2) const_local_iterator cbegin ( size_type n ) const;
返回const_iterator起點
返回一個const_iterator,指向unordered_map容器(1)或其中一個桶(2)中的第一個元素。
常量迭代器是指向const內容的迭代器。這個迭代器可以增加或減少(除非它本身也是const),就像unordered_map::begin返回的迭代器一樣,但是它不能用來修改它所指向的內容。
參數:
n:
桶數。這應該小於bucket_count。
它是一個可選參數,可以改變這個成員函數的行為:如果設置,迭代器將檢索到該桶的第一個元素,否則它將指向容器的第一個元素。
成員類型size_type是無符號整數類型。
返回值:
容器(1)或桶(2)中的第一個元素的迭代器。
const_iterator和const_local_iterator都是成員類型。在unordered_map類模板中,這些是正向迭代器類型。
const_local_iterator是與const_iterator相同類別的interator。它們的value_type、diffence_type、指針和引用成員類型也是相同的。但是迭代器本身不一定是相同類型的。
10)cend
container iterator (1) const_iterator cend() const noexcept;
bucket iterator (2) const_local_iterator cend ( size_type n ) const;
返回const_iterator結尾
返回一個const_iterator,指向unordered_map容器(1)或其中一個桶(2)中的past-the-end元素。
cend返回的const_iterator不指向任何元素,而是指向unordered_map容器中最后一個元素之后的位置(past-the-end),或者它的一個bucket(即,past-the-end的位置)。因此,返回的值不能取消引用——它通常用於描述范圍的開放端,比如[cbegin,cend)。
注意,unordered_map對象並不保證其元素的順序。但是,在任何情況下,從cbegin到cend的范圍覆蓋容器(或bucket)中的所有元素,直到失效。
const_iterator是指向const內容的迭代器。這個迭代器可以增加或減少(除非它本身也是const),就像unordered_map::end返回的迭代器一樣,但是它不能用來修改它所指向的內容。
參數:
n:
桶數。這應該小於bucket_count。
它是一個可選參數,可以改變這個成員函數的行為:如果設置,迭代器將檢索到該桶的第一個元素,否則它將指向容器的第一個元素。
成員類型size_type是無符號整數類型。
返回值:
元素的迭代器,遍歷容器(1)或桶(2)的末端。
const_iterator和const_local_iterator都是成員類型。在unordered_map類模板中,這些是正向迭代器類型。
const_local_iterator是與const_iterator相同類別的interator。它們的value_type、diffence_type、指針和引用成員類型也是相同的。但是迭代器本身不一定是相同類型的。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, string> mymap; mymap = {{"Australia", "canberra"}, {"U.S.", "Washington"}, {"France", "Paris"}}; cout << "mymap contains : "; for(auto it = mymap.cbegin(); it!=mymap.cend(); ++it) cout << " " << it->first << " : " << it->second; cout << endl; cout << "mymap's buckets contains: \n"; for(unsigned i = 0; i<mymap.bucket_count(); ++i){ cout << "bucket #" << i << " contains : "; for(auto local_it = mymap.cbegin(i); local_it!=mymap.cend(i); ++local_it) cout << " " <<local_it->first << " : " << local_it->second; cout << endl; } return 0; }
返回:
mymap contains : France : Paris U.S. : Washington Australia : canberra mymap's buckets contains: bucket #0 contains : bucket #1 contains : bucket #2 contains : France : Paris bucket #3 contains : U.S. : Washington Australia : canberra bucket #4 contains :
Element access元素訪問
11)operator[]
mapped_type& operator[] ( const key_type& k ); mapped_type& operator[] ( key_type&& k );
訪問元素
如果k匹配容器中元素的鍵,則該函數返回對其映射值的引用。
如果k不匹配容器中任何元素的鍵,則該函數用該鍵插入一個新元素並返回對其映射值的引用。請注意,即使沒有將映射值分配給元素(元素是使用其默認構造函數構造的),這也總是將容器大小增加1。
類似的成員函數unordered_map::at在具有鍵的元素存在時具有相同的行為,但在元素不存在時拋出異常。
參數:
k:
要訪問其映射值的元素的鍵值。
成員類型key_type是存儲在容器中的元素的鍵的類型,在unordered_map中定義為其第一個模板參數(鍵key)的別名。
如果是rvalue(第二個版本,右值引用),則在插入新元素時移動鍵而不是復制鍵。
返回值:
對元素的映射值的引用,其鍵值等效於k。
成員類型mapped_type是容器中映射值的類型,在unordered_map中定義為其第二個模板參數(T)的別名。
如果插入了新元素,則使用allocator_traits<allocator_type>::construct()分配它的存儲,這可能會在失敗時拋出異常(對於默認分配器,如果分配請求沒有成功,則拋出bad_alloc)。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, string> mymap; mymap["Bakery"] = "Barbara"; mymap["Seafood"] = "Lisa"; mymap["Produce"] = "John"; string name = mymap["Bakery"]; mymap["Seafood"] = name; mymap["Bakery"] = mymap["Produce"]; name = mymap["Deli"]; mymap["Produce"] = mymap["Gifts"]; for(auto& x:mymap) cout << x.first << ": " << x.second << endl; return 0; }
返回:
Deli:
Produce:
Gifts:
Seafood: Barbara
Bakery: John
12)at
mapped_type& at ( const key_type& k ); const mapped_type& at ( const key_type& k ) const;
訪問元素
返回對unordered_map中鍵為k的元素的映射值的引用。
如果k不匹配容器中任何元素的鍵,該函數將拋出out_of_range異常。
參數:
k:
要訪問其映射值的元素的鍵值。
成員類型key_type是存儲在容器中的元素的鍵的類型,在unordered_map中定義為其第一個模板參數(鍵key)的別名。
返回值:
對元素的映射值的引用,其鍵值等效於k。
成員類型mapped_type是容器中映射值的類型,在unordered_map中定義為其第二個模板參數(T)的別名。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, int> mymap = { {"Mars", 3000}, {"Saturn", 60000}, {"Jupiter", 70000} }; mymap.at("Mars") = 3396; mymap.at("Saturn") += 272; mymap.at("Jupiter") = mymap.at("Saturn") + 9638; for(auto& x : mymap){ cout << x.first << ": " << x.second << endl; } return 0; }
返回:
Jupiter: 69910 Saturn: 60272 Mars: 3396
Element lookup元素查看
13)find
iterator find ( const key_type& k ); const_iterator find ( const key_type& k ) const;
獲取元素的iterator
在容器中搜索以k為鍵的元素,如果找到了,就返回一個迭代器,否則就返回unordered_map::end(容器末尾的元素)的迭代器。
另一個成員函數unordered_map::count可用於檢查特定鍵是否存在。
還可以使用at或操作符[]的成員函數直接訪問映射值。
參數:
k:
要搜索的建值key。
成員類型key_type是容器中元素的鍵的類型,在unordered_map中定義為其第一個模板參數(key鍵)的別名。
返回值:
元素的迭代器(如果找到指定的鍵值),或者unordered_map::end(如果在容器中沒有找到指定的鍵)。
成員類型iterator和const_iterator是前向迭代器類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, double> mymap = { {"mom", 5.4}, {"dad", 6.1}, {"bro", 5.9} }; string input; cout << "who?"; getline(cin, input); unordered_map<string, double>::const_iterator got = mymap.find(input); if(got == mymap.end()) cout << "not found"; else cout << got->first << " is " << got->second; cout << endl; return 0; }
返回:
who?mom mom is 5.4
14)count
size_type count ( const key_type& k ) const;
用特定的鍵對元素計數
在容器中搜索鍵為k的元素,並返回找到的元素數量。因為unordered_map容器不允許重復的鍵,這意味着如果容器中存在具有該鍵的元素,則該函數實際返回1,否則返回0。
參數:
k:
要搜索的建值key。
成員類型key_type是容器中元素的鍵的類型,在unordered_map中定義為其第一個模板參數(key鍵)的別名。
返回值:
如果找到鍵值等於k的元素,則為1,否則為0。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string, double> mymap = { {"Burger", 2.99}, {"Fries", 1.99}, {"Soda", 1.50} }; for(auto& x : {"Burger", "Pizza", "Salad", "Soda"}){ if(mymap.count(x) > 0){ cout << "mymap has " << x << endl; }else{ cout << "mymap has no " << x << endl; } } return 0; }
返回:
mymap has Burger
mymap has no Pizza
mymap has no Salad
mymap has Soda
15)equal_range
pair<iterator,iterator> equal_range ( const key_type& k ); pair<const_iterator,const_iterator> equal_range ( const key_type& k ) const;
獲取具有特定鍵值的元素范圍
返回一個范圍的邊界,該范圍包含容器中所有的元素,其中鍵的值與k相比較。在unordered_map容器中,鍵是惟一的,該范圍最多包含一個元素。
如果k與容器中的任何鍵不匹配,則返回的范圍將end作為其上下范圍邊界。
參數:
k:
要搜索的建值key。
成員類型key_type是容器中元素的鍵的類型,在unordered_map中定義為其第一個模板參數(key鍵)的別名。
返回值:
函數返回一個對pair,其中它的成員pair::first是指向范圍下界的迭代器,pair::second是指向其上界的迭代器。范圍內的元素是這兩個迭代器之間的元素,包括pair::first,而不包括pair::second。
成員類型iterator和const_iterator是前向迭代器類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; using stringmap = unordered_map<string, string>; int main(){ stringmap myumm = { {"orange", "FL"}, {"strawberry", "LA"}, {"strawberry", "OK"}, {"pumpkin", "NH"} }; cout << "Entries with strawberry : "; auto range = myumm.equal_range("strawberry"); for_each( range.first, range.second, [](stringmap::value_type& x){cout << " " << x.second;} ); return 0; }
返回:
Entries with strawberry : LA
如果使用的是unordered_multimap:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; using stringmap = unordered_multimap<string, string>; stringmap merge(stringmap a, stringmap b){ stringmap temp{a}; temp.insert(b.begin(), b.end()); return temp; } int main(){ stringmap myumm = { {"orange", "FL"}, {"strawberry", "LA"}, {"strawberry", "OK"}, {"pumpkin", "NH"} }; cout << "Entries with strawberry : "; auto range = myumm.equal_range("strawberry"); for_each( range.first, range.second, [](stringmap::value_type& x){cout << " " << x.second;} ); return 0; }
返回:
Entries with strawberry : LA OK
Modifiers修改
16)emplace-如果該建值已有則不操作
template <class... Args> pair<iterator, bool> emplace ( Args&&... args );
構造和插入元素
如果unordered_map的鍵是惟一的,則在該元素中插入一個新元素。使用args作為元素構造函數的參數構造這個新元素。
只有在容器中沒有與被放置的鍵等價的鍵時才進行插入(unordered_map中的鍵是惟一的)。
如果插入,這將有效地將容器大小增加1。
存在一個類似的成員函數insert,它復制或將現有對象移動到容器中。
參數:
args:
參數,用於為插入的元素構造映射類型的新對象。
返回值:
如果發生插入的情況(因為不存在具有相同鍵值的其他元素),函數將返回一個pair對象,該對象的第一個組件是插入元素的迭代器,第二個組件為true。
否則,返回的pair對象的第一個組件是一個迭代器,它指向容器中具有相同鍵的元素,第二個組件是false。
成員類型迭代器是正向迭代器類型。
新元素的存儲是使用allocator_traits<allocator_type>::construct()分配的,它可能會在失敗時拋出異常(對於默認的分配器,如果分配請求沒有成功,就會拋出bad_alloc)。
17)emplace_hint
template <class... Args> iterator emplace_hint ( const_iterator position, Args&&... args );
使用提示來構造和插入元素
如果unordered_map的鍵是惟一的,則在該元素中插入一個新元素。使用args作為元素構造函數的參數構造這個新元素。position位置點指向容器中的一個位置,該位置提示從何處開始搜索其插入點(容器可能使用,也可能不使用此建議來優化插入操作)。
只有在容器中沒有與被放置的鍵等價的鍵時才進行插入(unordered_map中的鍵是惟一的)。
如果插入,這將有效地將容器大小增加1。
類似的成員函數insert也存在,它可以復制或將現有對象移動到容器中,也可以獲取位置提示。
參數:
position:
作為插入操作提示的位置。容器可以使用這個值來優化操作。
成員類型const_iterator是正向迭代器類型。
args:
參數,用於為插入的元素構造映射類型的新對象。
返回值:
容器中元素的迭代器,其鍵相當於新插入的元素。如果確實插入了新插入的元素,那么它將指向該元素;如果已經存在鍵,則指向具有等效鍵的現有元素(不替換它)。
成員類型迭代器是一個前向迭代器。
新元素的存儲是使用allocator_traits<allocator_type>::construct()分配的,它可能會在失敗時拋出異常(對於默認的分配器,如果分配請求沒有成功,就會拋出bad_alloc)。
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string,string> mymap; mymap.emplace("NCC-1701", "J.T. Kirk"); mymap.emplace("NCC-1701-D", "J.L. Picard"); mymap.emplace("NCC-74656", "K. Janeway"); mymap.emplace("NCC-1701", "new J.T. Kirk"); cout << "mymap contains : " << endl; for(auto& x:mymap) cout << x.first << ": " << x.second << endl; cout << endl; return 0; }
返回:
NCC-74656: K. Janeway NCC-1701-D: J.L. Picard NCC-1701: J.T. Kirk
18)insert-可同時插入多個
(1) pair<iterator,bool> insert ( const value_type& val );
(2) template <class P> pair<iterator,bool> insert ( P&& val );
(3) iterator insert ( const_iterator hint, const value_type& val );
(4) template <class P> iterator insert ( const_iterator hint, P&& val );
(5) template <class InputIterator> void insert ( InputIterator first, InputIterator last );
(6) void insert ( initializer_list<value_type> il );
插入元素
在unordered_map中插入新元素。
只有當每個元素的鍵不等於容器中已經存在的任何其他元素的鍵時,才會插入元素(unordered_map中的鍵是惟一的)。
這實際上增加了插入元素的數量,從而增加了容器的大小。
這些參數決定了插入了多少個元素,並將它們初始化為哪些值:
參數:
- val:
-
對象復制到新元素的值(或作為新元素的值移動)。
版本(1)和(3)復制元素(即val保存它的內容,容器保存一個副本)。
版本(2)和(4)移動元素(即 val將丟失它的內容,它將被容器中的新元素獲取)。
成員類型value_type是容器中元素的類型,在unordered_map中定義為對<const key_type,mapped_type>,其中成員類型key_type是第一個模板參數(key類型)的別名,而mapped_type是第二個模板參數(mapped映射類型,T)的別名。 - 只有當P是隱式轉換為value_type的類型時,才調用帶有P&&類型參數的簽名。
- hint:
- 迭代器到建議的位置,作為從何處開始搜索合適的插入點的提示。容器可能使用這個值,也可能不使用它來優化操作。元素將存儲在其相應的bucket中,而不管作為提示傳遞的是什么。
成員類型const_iterator是正向迭代器類型。
- first, last:
-
指定元素范圍的迭代器。將[first,last)范圍內的元素的副本插入到unordered_map容器中。
注意,范圍包括first和last之間的所有元素,包括first指向的元素,但不包括last指向的元素。
第一個和最后一個都不是目標容器中的迭代器。
模板類型可以是任何類型的輸入迭代器。
- il:
-
一個initializer_list對象。編譯器將從初始化器列表聲明器自動構造這些對象。
成員類型value_type容器中包含的元素的類型,定義在unordered_map一pair< key_type const, mapped_type >,成員類型相關聯是一個別名的第一個模板參數(key鍵類型),和mapped_type別名的第二個模板參數(mapped映射類型,T)。 - 返回值:
-
在版本(1)和(2)中,函數返回一個pair對象,該對象的第一個元素是一個迭代器,它指向容器中新插入的元素或鍵值相等的元素,並返回一個bool值,該值指示元素是否被成功插入。
在版本(3)和(4)中,函數返回一個迭代器,它要么指向容器中新插入的元素,要么指向鍵相同的元素。
版本(5)和(6)沒有返回任何值。
成員類型迭代器是正向迭代器類型。
新元素的存儲是使用allocator_traits<allocator_type>::construct()分配的,它可能會在失敗時拋出異常(對於默認的分配器,如果分配請求沒有成功,就會拋出bad_alloc)。 - 舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string, double> myrecipe, mypantry = {{"milk", 2.0}, {"flour", 1.5}}; pair<string, double> myshopping("barking powder", 0.3); myrecipe.insert(myshopping); myrecipe.insert(make_pair<string, double>("egg", 6.0)); myrecipe.insert({{"suger", 0.8},{"salt", 0.1}}); cout << "myrecipe contains : " << endl; for(auto& x : myrecipe) cout << x.first << " " << x.second << endl; cout << endl; return 0; }
返回:
myrecipe contains : suger 0.8 egg 6 salt 0.1 barking powder 0.3
19)erase
by position (1) iterator erase ( const_iterator position ); by key (2) size_type erase ( const key_type& k ); range (3) iterator erase ( const_iterator first, const_iterator last );
刪除元素
從unordered_map容器中刪除單個元素或一組元素([first,last])。
通過調用每個元素的析構函數,可以通過刪除的元素數量有效地減少容器的大小。
參數:
position:
指向要從unordered_map中刪除的單個元素的迭代器。
成員類型const_iterator是正向迭代器類型。
k:
要刪除的建值key。
成員類型key_type是容器中元素的鍵的類型,在unordered_map中定義為其第一個模板參數(key鍵)的別名。
- first, last:
-
迭代器在unordered_map容器中指定要刪除的范圍:[first,last)。即范圍包括first和last之間的所有元素,包括first指向的元素,但不包括last指向的元素。
注意,unordered_map容器並不遵循任何特定的順序來組織它的元素, 因此range刪除的效果可能不太容易預測。
成員類型const_iterator是正向迭代器類型。 - 返回值:
-
版本(1)和(3)返回一個迭代器,指向被擦除的最后一個元素之后的位置。
Version(2)返回被擦除的元素的數量,在unordered_map容器中(具有惟一鍵),如果存在鍵值為k的元素(因此隨后被擦除),則為1,否則為0。
成員類型迭代器是正向迭代器類型。
成員類型size_type是無符號整數類型。 - 舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string, string> mymap; // populating container: mymap["U.S."] = "Washington"; mymap["U.K."] = "London"; mymap["France"] = "Paris"; mymap["Russia"] = "Moscow"; mymap["China"] = "Beijing"; mymap["Germany"] = "Berlin"; mymap["Japan"] = "Tokyo"; for(auto& x:mymap) cout << x.first << " " << x.second << endl; cout << endl; mymap.erase(mymap.begin()); for(auto& x:mymap) cout << x.first << " " << x.second << endl; cout << endl; mymap.erase("France"); for(auto& x:mymap) cout << x.first << " " << x.second << endl; cout << endl; mymap.erase(mymap.find("U.S."), mymap.end()); for(auto& x:mymap) cout << x.first << " " << x.second << endl; cout << endl; return 0; }
返回:
/Users/user/CLionProjects/untitled/cmake-build-debug/untitled Japan Tokyo China Beijing U.S. Washington Russia Moscow Germany Berlin France Paris U.K. London China Beijing U.S. Washington Russia Moscow Germany Berlin France Paris U.K. London China Beijing U.S. Washington Russia Moscow Germany Berlin U.K. London China Beijing Process finished with exit code 0
20)clear
void clear() noexcept;
清除內容
將刪除unordered_map容器中的所有元素:調用它們的析構函數,並從容器中刪除它們,使其大小為0。
參數:
none
返回值:
none
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string,string> mymap = { {"house","maison"}, {"car","voiture"}, {"grapefruit","pamplemousse"} }; cout << "mymap contains : "; for(auto& x : mymap) cout << " " << x.first << "=" << x.second; cout << endl; mymap.clear(); mymap["hello"]="bonjour"; mymap["sun"]="soleil"; cout << "mymap contains : "; for(auto& x : mymap) cout << " " << x.first << "=" << x.second; cout << endl; return 0; }
返回:
mymap contains : grapefruit=pamplemousse car=voiture house=maison
mymap contains : sun=soleil hello=bonjour
21)swap
void swap ( unordered_map& ump );
交換內容
通過ump的內容交換容器的內容,ump是另一個包含相同類型元素的unordered_map對象。大小可能不同。
在調用這個成員函數之后,這個容器中的元素是在調用之前在ump中的元素,而ump中的元素是在這個容器中的元素。容器內部保存的其他對象(例如它們的hasher或key_equal對象)也被交換。
該函數在容器之間交換指向數據的內部指針,而不實際執行任何副本或對單個元素進行移動,因此無論大小,執行時間都是恆定的。
注意,全局算法函數的名稱是swap。為使unordered_map類型的參數具有與此成員函數相同的行為和復雜性,將重載此全局函數。
參數:
ump:
另一個與此類型相同的unordered_map容器對象。
返回值:
none
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<std::string,std::string> first = {{"Star Wars","G. Lucas"},{"Alien","R. Scott"},{"Terminator","J. Cameron"}}, second = {{"Inception","C. Nolan"},{"Donnie Darko","R. Kelly"}}; cout << "first contains : "; for(auto& x : first) cout << " " << x.first << "=" << x.second; cout << endl; cout << "second contains : "; for(auto& x : second) cout << " " << x.first << "=" << x.second; cout << endl; first.swap(second); cout << "first contains : "; for(auto& x : first) cout << " " << x.first << "=" << x.second; cout << endl; cout << "second contains : "; for(auto& x : second) cout << " " << x.first << "=" << x.second; cout << endl; return 0; }
返回:
first contains : Terminator=J. Cameron Alien=R. Scott Star Wars=G. Lucas second contains : Donnie Darko=R. Kelly Inception=C. Nolan first contains : Donnie Darko=R. Kelly Inception=C. Nolan second contains : Terminator=J. Cameron Alien=R. Scott Star Wars=G. Lucas
Buckets桶
22)bucket_count
size_type bucket_count() const noexcept;
桶數
返回unordered_map容器中的桶數。
bucket是容器內部哈希表中的一個槽,根據鍵的哈希值將元素賦給它。
桶的數量直接影響容器的哈希表的負載因子(從而影響碰撞的概率)。容器會自動增加桶的數量,以使負載因子低於特定的閾值(其max_load_factor),從而在每次需要增加桶的數量時重新散列。
參數:
none
返回值:
當前桶的數量。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; using stringmap = unordered_map<string, string>; stringmap merge(stringmap a, stringmap b){ stringmap temp{a}; temp.insert(b.begin(), b.end()); return temp; } int main(){ unordered_map<string,string> mymap = { {"house","maison"}, {"apple","pomme"}, {"tree","arbre"}, {"book","livre"}, {"door","porte"}, {"grapefruit","pamplemousse"} }; unsigned n = mymap.bucket_count(); std::cout << "mymap has " << n << " buckets.\n"; for (unsigned i=0; i<n; ++i) { cout << "bucket #" << i << " contains: "; for (auto it = mymap.begin(i); it!=mymap.end(i); ++it) cout << "[" << it->first << ":" << it->second << "] "; cout << "\n"; } return 0; }
返回:
/Users/user/CLionProjects/untitled/cmake-build-debug/untitled mymap has 11 buckets. bucket #0 contains: bucket #1 contains: [house:maison] bucket #2 contains: bucket #3 contains: [tree:arbre] bucket #4 contains: bucket #5 contains: bucket #6 contains: [grapefruit:pamplemousse] [door:porte] bucket #7 contains: bucket #8 contains: bucket #9 contains: bucket #10 contains: [apple:pomme] [book:livre] Process finished with exit code 0
23)max_bucket_count
size_type max_bucket_count() const noexcept;
返回最大桶數
返回unordered_map容器可以擁有的最大桶數。
這是由於系統約束或其庫實現的限制,容器可能擁有的最大桶數。
參數:
none
返回值:
最大桶數。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <unordered_map> using namespace std; int main(){ unordered_map<int,int> mymap; cout << "max_size = " << mymap.max_size() << endl; cout << "max_bucket_count = " << mymap.max_bucket_count() << endl; cout << "max_load_factor = " << mymap.max_load_factor() << endl; return 0; }
返回:
max_size = 768614336404564650 max_bucket_count = 768614336404564650 max_load_factor = 1
24)bucket_size
size_type bucket_size ( size_type n ) const;
返回桶大小
返回bucket n中元素的數量。
bucket是容器內部哈希表中的一個槽,根據鍵的哈希值將元素賦給它。
桶中元素的數量影響訪問桶中特定元素所需的時間。容器會自動增加桶的數量,以使裝載因子(即平均桶大小)低於其max_load_factor。
參數:
n:
桶數。
這應該低於bucket_count。
成員類型size_type是無符號整數類型。
返回值:
桶中元素的數目n。
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string,string> mymap = { {"us","United States"}, {"uk","United Kingdom"}, {"fr","France"}, {"de","Germany"} }; unsigned nbuckets = mymap.bucket_count(); cout << "mymap has " << nbuckets << " buckets : " << endl; for(unsigned i = 0; i<nbuckets; ++i) cout << "bucket # " << i << " has " << mymap.bucket_size(i) << " elements " << endl; return 0; }
返回:
mymap has 5 buckets : bucket # 0 has 1 elements bucket # 1 has 0 elements bucket # 2 has 0 elements bucket # 3 has 1 elements bucket # 4 has 2 elements
25)bucket
size_type bucket ( const key_type& k ) const;
定位元素的桶
返回鍵為k的元素所在的桶號。
bucket是容器內部哈希表中的一個槽,根據鍵的哈希值將元素賦給它。桶的編號從0到(bucket_count-1)。
可以通過unordered_map::begin和unordered_map::end返回的范圍迭代器訪問bucket中的各個元素。
參數:
k:
要定位其存儲桶的鍵值key。
成員類型key_type是容器中元素的鍵的類型,在unordered_map中定義為其第一個模板參數(key鍵)的別名。
返回值:
對應k的桶序列號
成員類型size_type是無符號整數類型。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,string> mymap = { {"us","United States"}, {"uk","United Kingdom"}, {"fr","France"}, {"de","Germany"} }; for (auto& x: mymap) { cout << "Element [" << x.first << ":" << x.second << "]"; cout << " is in bucket #" << mymap.bucket (x.first) << endl; } return 0; }
返回:
Element [de:Germany] is in bucket #0 Element [fr:France] is in bucket #3 Element [uk:United Kingdom] is in bucket #4 Element [us:United States] is in bucket #4
Hash policy
26) load_factor
float load_factor() const noexcept;
返回負載因子
返回unordered_map容器中的當前負載因子。
負載因子是容器中元素的數量(其大小)與桶的數量(bucket_count)之間的比率:
load_factor = size / bucket_count
在哈希表中,負載因素影響碰撞的概率(即兩個元素位於同一桶中的概率)。容器會自動增加桶的數量,以將負載因子保持在特定的閾值(其max_load_factor)之下,從而在每次需要擴展時導致重新散列。
要檢索或更改此閾值,請使用成員函數max_load_factor。
參數:
none
返回值:
當前的負載因子
舉例:
#include <iostream>
#include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,string> mymap = { {"us","United States"}, {"uk","United Kingdom"}, {"fr","France"}, {"de","Germany"} }; cout << "size = " << mymap.size() << endl; cout << "bucket_count = " << mymap.bucket_count() << endl; cout << "load_factor = " << mymap.load_factor() << endl; cout << "max_load_factor = " << mymap.max_load_factor() << endl; return 0; }
返回:
size = 4 bucket_count = 5 load_factor = 0.8 max_load_factor = 1
27)max_load_factor
get (1) float max_load_factor() const noexcept; set (2) void max_load_factor ( float z );
獲取或設置最大負載因子
第一個版本(1)返回unordered_map容器的當前最大負載因子。
第二個版本(2)將z設置為unordered_map容器的新最大負載因子。
負載因子是容器中元素的數量(其大小)與桶的數量(bucket_count)之間的比率。
默認情況下,unordered_map容器的max_load_factor為1.0。
在哈希表中,負載因素影響碰撞的概率。,兩個元素位於同一桶中的概率)。容器使用max_load_factor的值作為閾值,該閾值強制增加桶的數量(從而導致重新散列)。
但是請注意,該實現可能會對桶的數量施加上限(請參閱max_bucket_count),這可能會迫使容器忽略max_load_factor。
參數:
z:
新的最大負載因子
返回值:
當前的負載因子(僅對第一個get版本)
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,string> mymap = { {"Au","gold"}, {"Ag","Silver"}, {"Cu","Copper"}, {"Pt","Platinum"} }; cout << "current max_load_factor: " << mymap.max_load_factor() << endl; cout << "current size: " << mymap.size() << endl; cout << "current bucket_count: " << mymap.bucket_count() << endl; cout << "current load_factor: " << mymap.load_factor() << endl; float z = mymap.max_load_factor(); mymap.max_load_factor ( z / 2.0 ); //小於當前的負載因子則設為當前的,即為0.8,而不是0.5 cout << "[max_load_factor halved]" << endl; cout << endl; cout << "new max_load_factor: " << mymap.max_load_factor() << endl; cout << "new size: " << mymap.size() << endl; cout << "new bucket_count: " << mymap.bucket_count() << endl; cout << "new load_factor: " << mymap.load_factor() << endl; mymap.max_load_factor ( 0.9 ); cout << endl; cout << "new max_load_factor: " << mymap.max_load_factor() << endl; cout << "new size: " << mymap.size() << endl; cout << "new bucket_count: " << mymap.bucket_count() << endl; cout << "new load_factor: " << mymap.load_factor() << endl; return 0; }
返回:
/Users/user/CLionProjects/untitled/cmake-build-debug/untitled current max_load_factor: 1 current size: 4 current bucket_count: 5 current load_factor: 0.8 [max_load_factor halved] new max_load_factor: 0.8 new size: 4 new bucket_count: 5 new load_factor: 0.8 new max_load_factor: 0.9 new size: 4 new bucket_count: 5 new load_factor: 0.8 Process finished with exit code 0
28)rehash
void rehash( size_type n );
設置桶數
將容器中的桶數設置為n或更多。
如果n大於容器中當前桶的數量(bucket_count),則強制重新散列。新的bucket count可以等於或大於n。
如果n小於容器中桶的當前數量(bucket_count),則該函數可能對桶數沒有影響,也可能不會強制重新散列。
rehash是對哈希表的重構:容器中的所有元素根據它們的哈希值重新排列到新的bucket集合中。這可能會改變容器內元素迭代的順序。
每當容器的負載因子在操作中超過max_load_factor時,容器就會自動執行重列。
注意,這個函數的參數是桶的數量。存在一個類似的函數unordered_map::reserve,它期望容器中的元素數量作為參數。
參數:
n:
容器哈希表的最小桶數。
成員類型size_type是無符號整數類型。
返回值:
none
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,string> mymap; cout << "current bucket_count: " << mymap.bucket_count() << endl; mymap.rehash(20); mymap["house"] = "maison"; mymap["apple"] = "pomme"; mymap["tree"] = "arbre"; mymap["book"] = "livre"; mymap["door"] = "porte"; mymap["grapefruit"] = "pamplemousse"; cout << "current bucket_count: " << mymap.bucket_count() << endl; return 0; }
返回:
current bucket_count: 0 current bucket_count: 23 //結果可能大於或等於20
29)reserve
void reserve ( size_type n );
請求更改每個桶的容量
將容器中的桶數(bucket_count)設置為最適合包含至少n個元素。
如果n大於當前的bucket_count乘以max_load_factor,則容器的bucket_count將增加,並強制重新散列。
如果n小於這個值,函數可能沒有作用。
參數:
n:
所要求的元素數量為最小容量。
成員類型size_type是無符號整數類型
舉例:
#include <iostream> #include <string> #include <unordered_map> #include <algorithm> using namespace std; int main(){ unordered_map<string,string> mymap; mymap["house"] = "maison"; mymap["apple"] = "pomme"; mymap["tree"] = "arbre"; mymap["book"] = "livre"; mymap["door"] = "porte"; mymap["grapefruit"] = "pamplemousse"; cout << "current bucket_count: " << mymap.bucket_count() << endl; cout << "current max_load_factor: " << mymap.max_load_factor() << endl; for(unsigned i = 0; i<mymap.bucket_count(); ++i) cout << "current bucket_size: " << mymap.bucket_size(i) << endl; mymap.reserve(6); //n小於bucket_count*max_load_factor時 for (auto& x: mymap) { std::cout << x.first << ": " << x.second << std::endl; } cout << "current bucket_count: " << mymap.bucket_count() << endl; cout << "current max_load_factor: " << mymap.max_load_factor() << endl; for(unsigned i = 0; i<mymap.bucket_count(); ++i) cout << "current bucket_size: " << mymap.bucket_size(i) << endl; mymap.reserve(15);//n大於bucket_count*max_load_factor時 for (auto& x: mymap) { std::cout << x.first << ": " << x.second << std::endl; } cout << "current bucket_count: " << mymap.bucket_count() << endl; cout << "current max_load_factor: " << mymap.max_load_factor() << endl; for(unsigned i = 0; i<mymap.bucket_count(); ++i) cout << "current bucket_size: " << mymap.bucket_size(i) << endl; return 0; }
返回:
/Users/user/CLionProjects/untitled/cmake-build-debug/untitled current bucket_count: 11 current max_load_factor: 1 current bucket_size: 0 current bucket_size: 1 current bucket_size: 0 current bucket_size: 1 current bucket_size: 0 current bucket_size: 0 current bucket_size: 2 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 2 apple: pomme book: livre tree: arbre house: maison grapefruit: pamplemousse door: porte current bucket_count: 7 current max_load_factor: 1 current bucket_size: 0 current bucket_size: 1 current bucket_size: 1 current bucket_size: 2 current bucket_size: 0 current bucket_size: 1 current bucket_size: 1 apple: pomme grapefruit: pamplemousse book: livre tree: arbre house: maison door: porte current bucket_count: 17 current max_load_factor: 1 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 2 current bucket_size: 2 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 0 current bucket_size: 1 current bucket_size: 1 Process finished with exit code 0
通過使用unordered_map容器的期望大小(=6)來調用reserve,我們避免了容器大小的增加可能產生的多次重復哈希,並優化了哈希表的大小。
Observers
30)hash_function
hasher hash_function() const;
得到哈希函數
返回unordered_map容器使用的散列函數對象。
散列函數是一個一元函數,它接受類型為key_type的對象作為參數,並基於它返回類型為size_t的惟一值。它被構造中的容器所采用(有關更多信息,請參見unordered_map的構造函數unordered_map's constructor)。默認情況下,它是對應鍵類型的默認哈希函數:hash<key_type>。
參數:
none
返回值:
哈希函數。
成員類型hasher是容器使用的散列函數的類型,在unordered_map中定義為其第三個模板參數(Hash散列)的別名。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; using stringmap = unordered_map<string, string>; int main(){ stringmap mymap; stringmap::hasher fn = mymap.hash_function(); // 使用該hash函數求hash值 cout << "this: " << fn ("this") << endl; cout << "thin: " << fn ("thin") << endl; return 0; }
返回:
this: 1610705967341725939 thin: 3142588895646935236
31)key_eq
key_equal key_eq() const;
得到鍵等價謂詞
返回unordered_map容器使用的鍵等價比較謂詞。
鍵等價比較是一個謂詞,它接受鍵類型的兩個參數,並返回一個bool值,該值指示是否認為它們是等價的。它被構造中的容器所采用(有關更多信息,請參見unordered_map的構造函數)。默認情況下,它是equal_to<key_type>,返回的結果與將equal-to操作符(==)應用於參數相同。
參數:
none
返回值:
鍵相等比較對象。
成員類型key_equal是容器使用的鍵相等比較謂詞的類型,在unordered_map中定義為其第四個模板參數(Pred)的別名。
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main(){ unordered_map<string,string> mymap; bool case_insensitive = mymap.key_eq()("test","TEST"); //判斷是否大小寫敏感 cout << "mymap.key_eq() is "; cout << ( case_insensitive ? "case insensitive" : "case sensitive" ); cout << endl; return 0; }
返回:
mymap.key_eq() is case sensitive
可見是大小寫敏感的,說明返回的是false
32)get_allocator
allocator_type get_allocator() const noexcept;
得到分配器
返回用於構造容器的分配器對象。
參數:
none
返回值:
分配器。
成員類型allocator_type是容器使用的分配器的類型,在unordered_map中定義為其第五個模板參數(Alloc)的別名。
Non-member function overloads
33)operators
equality (1) template <class Key, class T, class Hash, class Pred, class Alloc> bool operator== ( const unordered_map<Key,T,Hash,Pred,Alloc>& lhs, const unordered_map<Key,T,Hash,Pred,Alloc>& rhs ); inequality (2) template <class Key, class T, class Hash, class Pred, class Alloc> bool operator!= ( const unordered_map<Key,T,Hash,Pred,Alloc>& lhs, const unordered_map<Key,T,Hash,Pred,Alloc>& rhs );
unordered_map的關系運算符
這些重載的全局操作符函數在unordered_map容器lhs和rhs之間執行適當的相等或不等比較操作。
平等比較的程序如下(如果程序找到一個結論性的答案,則在任何點停止):
首先,比較大小。
然后,在一個容器中查找另一個容器中的每個鍵,如果找到了,就比較它們的值。
注意,unordered_map::hash_function和unordered_map::key_eq對象在lhs和rhs中具有相同的行為。
參數:
- lhs, rhs:
- unordered_map容器(分別位於操作符的左側和右側),具有相同的模板參數(Key、T、Hash、Pred和Alloc)。
- 返回值:
- 相等則返回true,否則為false
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; using stringmap = unordered_map<string, string>; int main(){ stringmap a = { {"AAPL","Apple"}, {"MSFT","Microsoft"}, {"GOOG","Google"} }; stringmap b = { {"MSFT","Microsoft"}, {"GOOG","Google"}, {"AAPL","Apple"} }; stringmap c = { {"MSFT","Microsoft Corp."}, {"GOOG","Google Inc."}, {"AAPL","Apple Inc."} }; if (a==b) cout << "a and b are equal\n"; if (b!=c) cout << "b and c are not equal\n"; return 0; }
返回:
a and b are equal
b and c are not equal
34)swap
template <class Key, class T, class Hash, class Pred, class Alloc> void swap ( unordered_map<Key,T,Hash,Pred,Alloc>& lhs, unordered_map<Key,T,Hash,Pred,Alloc>& rhs );
交換兩個unordered_map容器的內容
容器lhs的內容與rhs的內容進行交換。兩個容器對象必須具有相同的類型(相同的模板參數),盡管大小可能不同。
調用這個函數之后,lhs中的元素是調用之前在rhs中的元素,rhs中的元素是在lhs中的元素。容器內部保存的其他對象(例如它們的hasher或key_equal對象)也被交換。
這是通用算法swap的一種特殊化,它通過交換內部的數據指針來提高性能,而不需要對單個元素執行任何復制或移動。
參數:
- lhs, rhs:
- unordered_map容器(分別位於操作符的左側和右側),具有相同的模板參數(Key、T、Hash、Pred和Alloc)。
- 返回值:
- none
舉例:
#include <iostream> #include <string> #include <unordered_map> using namespace std; using stringmap = unordered_map<string, string>; int main(){ stringmap first = {{"Star Wars","G. Lucas"},{"Alien","R. Scott"},{"Terminator","J. Cameron"}}, second = {{"Inception","C. Nolan"},{"Donnie Darko","R. Kelly"}}; cout << "first: "; for (auto& x: first) cout << x.first << " (" << x.second << "), "; cout << endl; cout << "second: "; for (auto& x: second) cout << x.first << " (" << x.second << "), "; cout << endl; swap(first,second); cout << "first: "; for (auto& x: first) cout << x.first << " (" << x.second << "), "; cout << endl; cout << "second: "; for (auto& x: second) cout << x.first << " (" << x.second << "), "; cout << endl; return 0; }
返回:
first: Terminator (J. Cameron), Alien (R. Scott), Star Wars (G. Lucas),
second: Donnie Darko (R. Kelly), Inception (C. Nolan),
first: Donnie Darko (R. Kelly), Inception (C. Nolan),
second: Terminator (J. Cameron), Alien (R. Scott), Star Wars (G. Lucas),
