std::unordered_map<Key,T,Hash,KeyEqual,Allocator>:: insert
|
std::
pair
<
iterator,
bool
>
insert
(
const
value_type
&
value
)
;
|
(1) | (自 C++11 起) |
|
std::
pair
<
iterator,
bool
>
insert
(
value_type
&&
value
)
;
|
(2) | (自 C++17 起) |
|
template
<
class
P
>
std:: pair < iterator, bool > insert ( P && value ) ; |
(3) | (自 C++11 起) |
|
iterator insert
(
const_iterator hint,
const
value_type
&
value
)
;
|
(4) | (自 C++11 起) |
|
iterator insert
(
const_iterator hint, value_type
&&
value
)
;
|
(5) | (自 C++17 起) |
|
template
<
class
P
>
iterator insert ( const_iterator hint, P && value ) ; |
(6) | (自 C++11 起) |
|
template
<
class
InputIt
>
void insert ( InputIt first, InputIt last ) ; |
(7) | (自 C++11 起) |
|
void
insert
(
std::
initializer_list
<
value_type
>
ilist
)
;
|
(8) | (自 C++11 起) |
|
insert_return_type insert
(
node_type
&&
nh
)
;
|
(9) | (自 C++17 起) |
|
iterator insert
(
const_iterator hint, node_type
&&
nh
)
;
|
(10) | (自 C++17 起) |
如果容器中尚未包含具有等效键的元素,则将元素插入容器。
如果在操作后新元素数量大于旧的
max_load_factor()
*
bucket_count()
,则会发生重哈希。
如果发生重哈希(由于插入操作),所有迭代器都会失效。否则(未发生重哈希),迭代器不会失效。
如果插入成功,当元素保存在节点句柄中时获取的该元素的指针和引用会失效,而在该元素被提取之前获取的指针和引用将变为有效。
(C++17 起)
目录 |
参数
| hint | - | 迭代器,作为插入内容的建议位置 |
| value | - | 要插入的元素值 |
| first, last | - | 定义要插入元素来源 范围 的迭代器对 |
| ilist | - | 要插入值的初始化列表 |
| nh | - | 兼容的 节点句柄 |
| 类型要求 | ||
-
InputIt
必须满足
LegacyInputIterator
的要求。
|
||
返回值
insert_return_type
类型的对象,其成员按以下方式初始化:
-
如果
nh
为空,则
inserted为 false ,position为 end ( ) ,且node为空。 -
否则如果插入成功,则
inserted为 true ,position指向被插入的元素,且node为空。 -
如果插入失败,则
inserted为 false ,node保留 nh 先前的值,且position指向一个键与 nh. key ( ) 等效的元素。
异常
复杂度
O(1)
,最坏情况
O(size())
。
O(N)
,其中 N 为待插入元素的数量。最坏情况:
O(N * size() + N)
。
O(1)
,最坏情况
O(size())
。
注释
提示插入
(
(
4-6
)
和
(
10
)
)
不返回布尔值,这是为了与顺序容器(如
std::vector::insert
)的位置插入操作保持签名兼容。这使得创建通用插入器(如
std::inserter
)成为可能。检查提示插入是否成功的一种方法是比较插入前后的
size()
。
示例
#include <iostream> #include <string> #include <unordered_map> int main () { std::unordered_map<int, std::string> dict = {{1, "one"}, {2, "two"}}; dict.insert({3, "three"}); dict.insert(std::make_pair(4, "four")); dict.insert({{4, "another four"}, {5, "five"}}); const bool ok = dict.insert({1, "another one"}).second; std::cout << "inserting 1 => \"another one\" " << (ok ? "succeeded" : "failed") << '\n'; std::cout << "contents:\n"; for (auto& p : dict) std::cout << ' ' << p.first << " => " << p.second << '\n'; }
可能的输出:
inserting 1 => "another one" failed contents: 5 => five 1 => one 2 => two 3 => three 4 => four
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| DR | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2005 | C++11 |
重载版本
(
3
)
和
(
6
)
仅在
P
可隐式转换为
value_type
时
参与重载决议 |
仅在
value_type
可从
P
&&
构造时参与决议 |
参见
|
原地构造元素
(公开成员函数) |
|
|
使用提示原地构造元素
(公开成员函数) |
|
|
(C++17)
|
插入元素,若键已存在则赋值给当前元素
(公开成员函数) |
|
创建从参数推断类型的
std::insert_iterator
(函数模板) |