命名空间
变体
操作

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::extract

来自 cppreference.cn
 
 
 
 
node_type extract( const_iterator position );
(1) (since C++17)
node_type extract( const Key& k );
(2) (since C++17)
template< class K >
node_type extract( K&& x );
(3) (since 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 是更改映射元素的键而不重新分配的唯一方法

std::map<int, std::string> m{{1, "mango"}, {2, "papaya"}, {3, "guava"}};
auto nh = m.extract(2);
nh.key() = 4;
m.insert(std::move(nh));
// m == {{1, "mango"}, {3, "guava"}, {4, "papaya"}}
特性测试 Std 特性
__cpp_lib_associative_heterogeneous_erasure 202110L (C++23) 关联容器无序关联容器中的异质擦除,(3)

[edit] 示例

#include <algorithm>
#include <iostream>
#include <string_view>
#include <unordered_map>
 
void print(std::string_view comment, const auto& data)
{
    std::cout << comment;
    for (auto [k, v] : data)
        std::cout << ' ' << k << '(' << v << ')';
 
    std::cout << '\n';
}
 
int main()
{
    std::unordered_map<int, char> cont{{1, 'a'}, {2, 'b'}, {3, 'c'}};
 
    print("Start:", cont);
 
    // Extract node handle and change key
    auto nh = cont.extract(1);
    nh.key() = 4;
 
    print("After extract and before insert:", cont);
 
    // Insert node handle back
    cont.insert(std::move(nh));
 
    print("End:", cont);
}

可能的输出

Start: 1(a) 2(b) 3(c)
After extract and before insert: 2(b) 3(c)
End: 2(b) 3(c) 4(a)

[edit] 参见

(C++17)
从另一容器拼接节点
(public member function) [编辑]
插入元素或节点(since C++17)
(public member function) [编辑]
擦除元素
(public member function) [编辑]