命名空间
变体
操作

std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::extract

来自 cppreference.cn
 
 
 
 
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 起)
1) 解链包含由 position 所指向元素的节点,并返回拥有它的 节点句柄
2) 如果容器拥有与 k 等价的键的元素,则解链包含首个这种元素的节点,并从容器返回拥有它的 节点句柄。否则,返回空节点句柄。
3)(2) 相同。此重载仅在 Hash::is_transparentKeyEqual::is_transparent 合法且各自表示类型,且 iteratorconst_iterator 均非隐式可从 K 转换而来时参与重载决议。这假定这种 Hash 可用 KKey 类型调用,且 KeyEqual 是透明的,它们一起允许在不构造 Key 实例的情况下调用此函数。

在任一情况下,均不复制或移动元素,仅重指向容器节点的内部指针。

提取节点仅会使指向被提取元素的迭代器失效,并保持未擦除元素的相对顺序。指向被提取元素的指针和引用保持有效,但在元素为节点句柄所拥有时不可用:若元素被插入到容器中,则它们变为可用。

内容

[edit] 参数

position - 指向此容器中有效迭代器
k - 用于标识要提取节点的键
x - 可以与标识要提取节点的键透明比较的任何类型的值

[edit] 返回值

拥有被提取元素的 节点句柄,或者在 (2,3) 中找不到元素的情况下为空节点句柄。

[edit] 异常

1) 不抛出任何异常。
2,3)HashKeyEqual 对象抛出的任何异常。

[edit] 复杂度

1,2,3) 平均情况 O(1),最坏情况 O(size())。

[edit] 注解

extract 是将仅可移动对象从 set 中取出的唯一方法

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)

[edit] 示例

#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_multiset<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

[edit] 参见

(C++17)
从另一容器拼接节点
(公开成员函数) [编辑]
插入元素 或节点(自 C++17 起)
(公开成员函数) [编辑]
擦除元素
(公开成员函数) [编辑]