std::multimap<Key,T,Compare,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) |
3) 与 (2) 相同。此重载仅在限定标识符 Compare::is_transparent 合法且表示类型,且
iterator
或 const_iterator
均不能从 K
隐式转换时参与重载决议。它允许在不构造 Key
实例的情况下调用此函数。在任何情况下,元素都不会被复制或移动,只有容器节点的内部指针会被重定向(可能发生重新平衡,如同 erase() 一样)。
提取节点仅会使指向被提取元素的迭代器失效。指向被提取元素的指针和引用仍然有效,但在元素被节点句柄拥有时不能使用:如果元素被插入到容器中,它们将变为可用。
内容 |
[edit] 参数
position | - | 此容器中的有效迭代器 |
k | - | 用于标识要提取的节点的键 |
x | - | 任何类型的数值,可以与标识要提取的节点的键透明地比较 |
[edit] 返回值
一个拥有提取元素的节点句柄,或者在 (2,3) 中未找到元素的情况下为空节点句柄。
[edit] 异常
1) 不抛出任何异常。
2,3) 由
Compare
对象抛出的任何异常。[edit] 复杂度
1) 分期摊销常数。
2,3) log(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"}}
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_associative_heterogeneous_erasure |
202110L |
(C++23) | 关联容器和无序关联容器中的异构擦除,(3) |
[edit] 示例
运行此代码
#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::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) |
插入元素 或 节点(since C++17) (public member function) | |
擦除元素 (public member function) |