std::map<Key,T,Compare,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
。若键不存在,则执行插入操作,如同通过
insert
方法,从
value_type
(
k,
std::
forward
<
M
>
(
obj
)
)
构造新值。
mapped_type
。若键不存在,则使用
std::
forward
<
K
>
(
k
)
,
std::
forward
<
M
>
(
obj
)
)
构造
value_type
类型的对象
u
,然后将
u
插入到
*
this
中。若
equal_range
(
u.
first
)
==
equal_range
(
k
)
为
false
,则行为未定义。
value_type
必须能从
std::
forward
<
K
>
(
k
)
,
std::
forward
<
M
>
(
obj
)
可就位构造
到
map
中。此重载仅当
Compare
为
透明
时才参与重载决议。它允许在不构造
Key
实例的情况下调用此函数。
行为未定义 (C++20 前) 程序非良构 (C++20 起) ,若 std:: is_assignable_v < mapped_type & , M && > 为 false 。
不会使任何迭代器或引用失效。
目录 |
参数
| k | - | 用于查找且在未找到时插入的键 |
| hint | - | 指向新元素将插入位置之前的迭代器 |
| obj | - | 要插入或赋值的值 |
返回值
复杂度
emplace
相同。
emplace_hint
相同。
注解
insert_or_assign
比
operator
[
]
返回更多信息,且不要求映射类型具有默认构造特性。
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_map_try_emplace
|
201411L
|
(C++17) |
std::map::try_emplace
,
std::map::insert_or_assign
|
__cpp_lib_associative_heterogeneous_insertion
|
202311L
|
(C++26) | 有序 和 无序 关联 容器 中剩余成员函数的异构重载。包含 ( 3 ) 和 ( 6 ) 版本重载。 |
示例
#include <iostream> #include <string> #include <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::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 [a] = apple [b] = banana [c] = clementine
参见
|
访问或插入指定元素
(公开成员函数) |
|
|
带边界检查的指定元素访问
(公开成员函数) |
|
|
插入元素
或节点
(C++17 起)
(公开成员函数) |
|
|
(C++11)
|
原位构造元素
(公开成员函数) |