std::set<Key,Compare,Allocator>:: extract
From cppreference.net
|
node_type extract
(
const_iterator pos
)
;
|
(1) |
(自 C++17 起)
(自 C++26 起为 constexpr) |
|
node_type extract
(
const
Key
&
k
)
;
|
(2) |
(自 C++17 起)
(自 C++26 起为 constexpr) |
|
template
<
class
K
>
node_type extract ( K && x ) ; |
(3) |
(自 C++23 起)
(自 C++26 起为 constexpr) |
3)
此重载仅当
Compare
满足
透明性要求
,且
iterator
与
const_iterator
均不能从
K
隐式转换时,才参与重载决议。该特性允许在不构造
Key
实例的情况下调用此函数。
无论哪种情况,都不会复制或移动元素,仅重新指向容器节点的内部指针(可能会发生重新平衡,如同 erase() 操作)。
提取节点只会使指向被提取元素的迭代器失效。指向被提取元素的指针和引用仍然保持有效,但当元素由节点句柄持有时不可使用:若元素被插入容器后即可重新使用。
目录 |
参数
| pos | - | 指向该容器的有效迭代器 |
| k | - | 用于标识待提取节点的键 |
| x | - | 可与标识待提取节点的键进行透明比较的任意类型值 |
返回值
一个 node handle ,它拥有被提取的元素,或者在 (2,3) 中未找到该元素时返回空的node handle。
异常
1)
不抛出任何异常。
2,3)
由
Compare
对象抛出的任何异常。
复杂度
1)
摊还常量。
2,3)
log(
size()
)
注释
extract 是唯一能从集合中取出仅移动对象的方式:
std::set<move_only_type> s; s.emplace(...); move_only_type mot = std::move(s.extract(s.begin()).value());
| 功能测试 宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_associative_heterogeneous_erasure
|
202110L
|
(C++23) | 关联容器 与 无序关联容器 中的异构擦除操作, ( 3 ) |
示例
运行此代码
#include <algorithm> #include <iostream> #include <string_view> #include <set> void print(std::string_view comment, const auto& data) { std::cout << comment; for (auto datum : data) std::cout << ' ' << datum; std::cout << '\n'; } int main() { std::set<int> cont{1, 2, 3}; print("Start:", cont); // 提取节点句柄并修改键值 auto nh = cont.extract(1); nh.value() = 4; print("After extract and before insert:", cont); // 将节点句柄插回容器 cont.insert(std::move(nh)); print("End:", cont); }
输出:
Start: 1 2 3 After extract and before insert: 2 3 End: 2 3 4
另请参阅
|
(C++17)
|
从另一容器接合节点
(公开成员函数) |
|
插入元素
或节点
(C++17 起)
(公开成员函数) |
|
|
擦除元素
(公开成员函数) |