命名空间
变体
操作

std::unordered_multimap<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 指向的元素所在的节点,并返回拥有它的 node handle
2) 如果容器中存在键等价于 k 的元素,则解除链接容器中首个这种元素所在的节点,并返回拥有它的 node handle。否则,返回一个空节点句柄。
3)(2) 相同。此重载仅在 Hash::is_transparentKeyEqual::is_transparent 有效且各自表示一种类型,且 iteratorconst_iterator 都不能从 K 隐式转换时参与重载决议。 这假定此类 Hash 可以使用 KKey 类型调用,并且 KeyEqual 是透明的,这两者共同允许在不构造 Key 实例的情况下调用此函数。

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

提取节点仅会使指向被提取元素的迭代器失效,并保留未擦除元素的相对顺序。指向被提取元素的指针和引用仍然有效,但在元素由节点句柄拥有时无法使用:如果元素被插入到容器中,它们将变为可用。

内容

[edit] 参数

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

[edit] 返回值

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

[edit] 异常

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

[edit] 复杂度

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

[edit] 注解

extract 是在不重新分配的情况下更改 map 元素键的唯一方法

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"}}
Feature-test 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_multimap<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) [edit]
插入元素 或节点(since C++17)
(public member function) [edit]
擦除元素
(public member function) [edit]