std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::operator[]
來自 cppreference.com
T& operator[]( const Key& key ); |
(1) | (C++23 起) |
T& operator[]( Key&& key ); |
(2) | (C++23 起) |
template< class K > T& operator[]( K&& x ); |
(3) | (C++23 起) |
返回對映到等效於 key 或 x 的鍵的值的引用,如果該鍵尚不存在,則執行插入。
等價於 return this->try_emplace(std::forward<K>(x)).first->second;。此過載僅在限定 ID Compare::is_transparent 有效並表示一種型別時才參與過載決議。它允許在不構造
Key
例項的情況下呼叫此函式。迭代器失效資訊從 此處 複製 |
目錄 |
[編輯] 引數
key | - | 要查詢的元素的鍵 |
x | - | 可與鍵透明比較的任何型別的值 |
[編輯] 返回值
1,2) 如果不存在鍵為 key 的元素,則返回新元素的對映值的引用。否則,返回現有元素的對映值的引用,其鍵等效於 key。
3) 如果不存在與值 x 比較等效的鍵的元素,則返回新元素的對映值的引用。否則,返回現有元素的對映值的引用,其鍵與 x 比較等效。
[編輯] 異常
如果任何操作丟擲異常,則插入無效。
[編輯] 複雜度
容器大小的對數級,加上(如果存在)插入空元素的開銷。
[編輯] 注意
operator[] 是非 const 的,因為它在鍵不存在時插入鍵。如果不需要這種行為,或者容器是 const,可以使用 at
。
insert_or_assign
返回比 operator[] 更多的資訊,並且不需要對映型別是可預設構造的。
[編輯] 示例
執行此程式碼
#include <iostream> #include <string> #include <flat_map> void println(auto const comment, auto const& map) { std::cout << comment << '{'; for (const auto& pair : map) std::cout << '{' << pair.first << ": " << pair.second << '}'; std::cout << "}\n"; } int main() { std::flat_map<char, int> letter_counts{{'a', 27}, {'b', 3}, {'c', 1}}; println("letter_counts initially contains: ", letter_counts); letter_counts['b'] = 42; // updates an existing value letter_counts['x'] = 9; // inserts a new value println("after modifications it contains: ", letter_counts); // count the number of occurrences of each word // (the first call to operator[] initialized the counter with zero) std::flat_map<std::string, int> word_map; for (const auto& w : {"this", "sentence", "is", "not", "a", "sentence", "this", "sentence", "is", "a", "hoax"}) ++word_map[w]; word_map["that"]; // just inserts the pair {"that", 0} for (const auto& [word, count] : word_map) std::cout << count << " occurrence(s) of word '" << word << "'\n"; }
輸出
letter_counts initially contains: {{a: 27}{b: 3}{c: 1}} after modifications it contains: {{a: 27}{b: 42}{c: 1}{x: 9}} 2 occurrence(s) of word 'a' 1 occurrence(s) of word 'hoax' 2 occurrence(s) of word 'is' 1 occurrence(s) of word 'not' 3 occurrence(s) of word 'sentence' 0 occurrence(s) of word 'that' 2 occurrence(s) of word 'this'
[編輯] 另請參閱
訪問指定的元素,帶邊界檢查 (public 成員函式) | |
插入元素或如果鍵已存在則賦值給當前元素 (public 成員函式) | |
如果鍵不存在則原地插入,如果鍵存在則不執行任何操作 (public 成員函式) |