std::flat_map<Key,T,Compare,KeyContainer,MappedContainer>::operator[]
来自 cppreference.cn
                    
                                        
                    
                    
                                                            
                    
| 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 成员函数) | 


