std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: insert_or_assign
|
template
<
class
M
>
std:: pair < iterator, bool > insert_or_assign ( const Key & k, M && obj ) ; |
(1) | (自 C++17 起) |
|
template
<
class
M
>
std:: pair < iterator, bool > insert_or_assign ( Key && k, M && obj ) ; |
(2) | (自 C++17 起) |
|
template
<
class
K,
class
M
>
std:: pair < iterator, bool > insert_or_assign ( K && k, M && obj ) ; |
(3) | (自 C++26 起) |
|
template
<
class
M
>
iterator insert_or_assign ( const_iterator hint, const Key & k, M && obj ) ; |
(4) | (自 C++17 起) |
|
template
<
class
M
>
iterator insert_or_assign ( const_iterator hint, Key && k, M && obj ) ; |
(5) | (自 C++17 起) |
|
template
<
class
K,
class
M
>
iterator insert_or_assign ( const_iterator hint, K && k, M && obj ) ; |
(6) | (自 C++26 起) |
mapped_type
。若键不存在,则执行插入操作,通过
value_type
(
k,
std::
forward
<
M
>
(
obj
)
)
构造新值,如同通过
insert
插入。
mapped_type
。若键不存在,则使用
std::
forward
<
K
>
(
k
)
,
std::
forward
<
M
>
(
obj
)
)
构造一个
value_type
类型的对象
u
,然后将
u
插入到
*
this
中。若
hash_function
(
)
(
u.
first
)
!
=
hash_function
(
)
(
k
)
||
contains
(
u.
first
)
为
true
,则行为未定义。
value_type
必须能从
std::
forward
<
K
>
(
k
)
,
std::
forward
<
M
>
(
obj
)
进行
EmplaceConstructible
到
unordered_map
中。此重载仅当
Hash
和
KeyEqual
均为
transparent
时参与重载决议。这要求
Hash
可同时被
K
和
Key
类型调用,且
KeyEqual
是透明的,从而允许在不构造
Key
实例的情况下调用此函数。
行为未定义 (C++20 前) 程序非良构 (C++20 起) ,若 std:: is_assignable_v < mapped_type & , M && > 为 false 。
如果在操作后新元素数量大于旧的
max_load_factor()
*
bucket_count()
将发生重新哈希。
如果发生重新哈希(由于插入操作),所有迭代器将失效。否则(未发生重新哈希),迭代器不会失效。
目录 |
参数
| k | - | 用于查找且在未找到时插入的键 |
| hint | - | 指向新元素将插入位置之前的迭代器 |
| obj | - | 要插入或赋值的值 |
返回值
复杂度
emplace
相同。
emplace_hint
的情况相同。
说明
insert_or_assign
比
operator
[
]
返回更多信息,且不要求映射类型具有默认构造特性。
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_unordered_map_try_emplace
|
201411L
|
(C++17) |
std::unordered_map::try_emplace
,
std::unordered_map::insert_or_assign
|
__cpp_lib_associative_heterogeneous_insertion
|
202311L
|
(C++26) | 有序 和 无序 关联 容器 中剩余成员函数的异构重载。重载版本 ( 3 ) 和 ( 6 ) 。 |
示例
#include <iostream> #include <string> #include <unordered_map> void print_node(const auto& node) { std::cout << '[' << node.first << "] = " << node.second << '\n'; } void print_result(auto const& pair) { std::cout << (pair.second ? "inserted: " : "assigned: "); print_node(*pair.first); } int main() { std::unordered_map<std::string, std::string> myMap; print_result(myMap.insert_or_assign("a", "apple")); print_result(myMap.insert_or_assign("b", "banana")); print_result(myMap.insert_or_assign("c", "cherry")); print_result(myMap.insert_or_assign("c", "clementine")); for (const auto& node : myMap) print_node(node); }
可能的输出:
inserted: [a] = apple inserted: [b] = banana inserted: [c] = cherry assigned: [c] = clementine [c] = clementine [a] = apple [b] = banana
参见
|
访问或插入指定元素
(公开成员函数) |
|
|
带边界检查的指定元素访问
(公开成员函数) |
|
|
插入元素
或节点
(C++17 起)
(公开成员函数) |
|
|
原位构造元素
(公开成员函数) |