std::unordered_set<Key,Hash,KeyEqual,Allocator>::extract
来自 cppreference.cn
< cpp | container | unordered set
node_type extract( const_iterator position ); |
(1) | (自 C++17 起) |
node_type extract( const Key& k ); |
(2) | (自 C++17 起) |
template< class K > node_type extract( K&& x ); |
(3) | (自 C++23 起) |
3) 与 (2) 相同。此重载仅在以下情况参与重载决议:Hash::is_transparent 和 KeyEqual::is_transparent 都是有效的且各自表示一个类型,并且
iterator
和 const_iterator
都不能从 K
隐式转换而来。 这假定此 Hash
可使用 K
和 Key
类型调用,并且 KeyEqual
是透明的,这二者共同允许在不构造 Key
实例的情况下调用此函数。在任一情况下,都不会复制或移动元素,仅容器节点的内部指针被重定向。
提取节点仅会使指向被提取元素的迭代器失效,并保留未被擦除元素的相对顺序。指向被提取元素的指针和引用仍然有效,但在元素由节点句柄拥有时不能使用:如果元素被插入到容器中,它们将变为可用。
内容 |
[编辑] 参数
position | - | 指向此容器的有效迭代器 |
k | - | 用于标识要提取的节点的键 |
x | - | 任何类型的数值,可以与标识要提取的节点的键透明地比较 |
[编辑] 返回值
拥有已提取元素的节点句柄,或者在 (2,3) 中未找到元素的情况下为空节点句柄。
[编辑] 异常
1) 不抛出任何异常。
2,3) 由
Hash
和 KeyEqual
对象抛出的任何异常。[编辑] 复杂度
1,2,3) 平均情况 O(1),最坏情况 O(size())。
[编辑] 注释
extract 是从 set 中取出仅可移动 (move-only) 对象的唯一方法
std::set<move_only_type> s; s.emplace(...); move_only_type mot = std::move(s.extract(s.begin()).value());
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_associative_heterogeneous_erasure |
202110L |
(C++23) | 关联容器和无序关联容器中的异构擦除,(3) |
[编辑] 示例
运行此代码
#include <algorithm> #include <iostream> #include <string_view> #include <unordered_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::unordered_set<int> cont{1, 2, 3}; print("Start:", cont); // Extract node handle and change key auto nh = cont.extract(1); nh.value() = 4; print("After extract and before insert:", cont); // Insert node handle back 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 起) (公共成员函数) | |
擦除元素 (公共成员函数) |