std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: operator[]
|
T
&
operator
[
]
(
const
Key
&
key
)
;
|
(1) | (C++11 起) |
|
T
&
operator
[
]
(
Key
&&
key
)
;
|
(2) | (C++11 起) |
|
template
<
class
K
>
T & operator [ ] ( K && x ) ; |
(3) | (C++26 起) |
返回对映射到与 key 或 x 等价键所对应值的引用,若该键尚不存在则执行插入操作。
value_type
对象。
key
复制构造,且映射值进行
值初始化
。
-
value_type
必须能从
std::
piecewise_construct
,
std::
forward_as_tuple
(
key
)
,
std::
tuple
<>
(
)
进行
就地构造
。使用默认分配器时,这意味着
key_type
必须为
可复制构造
,且
mapped_type
必须为
可默认构造
。
|
value_type
对象。
使用默认分配器时,这会导致键从
key
移动构造,且映射值进行
值初始化
。
-
value_type
必须能从
std::
piecewise_construct
,
std::
forward_as_tuple
(
std
::
move
(
key
)
)
,
std::
tuple
<>
(
)
进行
原位构造
。使用默认分配器时,这意味着
key_type
必须为
可移动构造
,且
mapped_type
必须为
可默认构造
。
|
Hash
与
KeyEqual
均为
透明
时参与重载决议。这要求该
Hash
可同时被
K
和
Key
类型调用,且
KeyEqual
是透明的,共同使得无需构造
Key
实例即可调用此函数。
如果在操作后新元素数量大于旧的
max_load_factor()
*
bucket_count()
将发生重新哈希。
如果发生重新哈希(由于插入操作),所有迭代器将失效。否则(未发生重新哈希),迭代器不会失效。
目录 |
参数
| key | - | 要查找元素的键 |
| x | - | 可与键进行透明比较的任意类型值 |
返回值
异常
如果任何操作抛出异常,则插入操作不会产生任何效果。
复杂度
平均情况:常数复杂度,最坏情况:与容器大小呈线性关系。
注释
在已发布的C++11和C++14标准中,此函数曾被要求
mapped_type
需满足
可默认插入
条件,且
key_type
需满足
可拷贝插入
或
可移动插入
*
this
的要求。该规范存在缺陷,后由
LWG问题2469
修复,上文描述已包含该问题的解决方案。
然而,已知某个实现(libc++)会通过两次独立的分配器
construct()
调用来构造
key_type
和
mapped_type
对象——这 arguably 符合已发布标准的要求——而非直接置入
value_type
对象。
operator
[
]
是非常量函数,因为它会在键不存在时插入该键。若不需要此行为或容器为
const
状态,可使用
at
方法。
|
|
(since C++17) |
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_associative_heterogeneous_insertion
|
202311L
|
(C++26) | 为 有序 和 无序 关联 容器 中剩余成员函数提供异构重载。 ( 3 ) |
示例
#include <iostream> #include <string> #include <unordered_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::unordered_map<char, int> letter_counts{{'a', 27}, {'b', 3}, {'c', 1}}; println("letter_counts initially contains: ", letter_counts); letter_counts['b'] = 42; // 更新现有值 letter_counts['x'] = 9; // 插入新值 println("after modifications it contains: ", letter_counts); // 统计每个单词的出现次数 //(首次调用 operator[] 会将计数器初始化为零) std::unordered_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"]; // 仅插入键值对 {"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'
参见
|
访问指定元素并进行边界检查
(公开成员函数) |
|
|
(C++17)
|
插入元素,若键已存在则赋值给当前元素
(公开成员函数) |
|
(C++17)
|
若键不存在则就地插入,若键存在则不执行任何操作
(公开成员函数) |