命名空间
变体
操作

std::map<Key,T,Compare,Allocator>::extract

来自 cppreference.cn
< cpp‎ | 容器‎ | map
 
 
 
 
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) 相同。此重载仅在限定标识符 Compare::is_transparent 有效并表示类型,且 iteratorconst_iterator 都不能从 K 隐式转换时参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

在任何情况下,都不会复制或移动元素,仅重新指向容器节点的内部指针(可能发生重新平衡,如同 erase())。

抽取节点仅使指向被抽取元素的迭代器失效。指向被抽取元素的指针和引用仍然有效,但在元素由节点句柄拥有时不能使用:如果元素被插入到容器中,它们将变为可用。

内容

[编辑] 参数

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

[编辑] 返回值

一个 节点句柄,拥有被抽取的元素;如果元素未在 (2,3) 中找到,则为空节点句柄。

[编辑] 异常

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

[编辑] 复杂度

1) 均摊常数。
2,3) log(size())

[编辑] 注解

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"}}
特性测试 Std 特性
__cpp_lib_associative_heterogeneous_erasure 202110L (C++23) 关联容器无序关联容器中的异构擦除,(3)

[编辑] 示例

#include <algorithm>
#include <iostream>
#include <string_view>
#include <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::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)

[编辑] 参见

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