std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::extract
來自 cppreference.com
| 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 起) |
3) 同 (2)。此過載僅在 Hash::is_transparent 和 KeyEqual::is_transparent 有效且都表示一個型別,並且
iterator 和 const_iterator 都不能從 K 隱式轉換時才參與過載決議。這假定此類 Hash 可以與 K 和 Key 型別一起呼叫,並且 KeyEqual 是透明的,這使得無需構造 Key 例項即可呼叫此函式。在任何情況下,都不會複製或移動元素,只有容器節點的內部指標被重新指向。
提取節點僅使指向被提取元素的迭代器失效,並保留未被擦除元素的相對順序。指向被提取元素的指標和引用仍然有效,但在元素被節點控制代碼擁有時不能使用:如果元素被插入到容器中,它們將變得可用。
目錄 |
[編輯] 引數
| position | - | 指向此容器的有效迭代器 |
| k | - | 用於標識要提取節點的鍵 |
| x | - | 可與要提取節點的鍵進行透明比較的任意型別的值 |
[編輯] 返回值
一個擁有被提取元素的節點控制代碼,如果在 (2,3) 中未找到元素,則為空節點控制代碼。
[編輯] 異常
1) 不丟擲任何異常。
2,3) 由
Hash 和 KeyEqual 物件丟擲的任何異常。[編輯] 複雜度
1,2,3) 平均情況 O(1),最壞情況 O(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"}}
| 特性測試宏 | 值 | 標準 | 特性 |
|---|---|---|---|
__cpp_lib_associative_heterogeneous_erasure |
202110L |
(C++23) | 關聯容器和無序關聯容器中的異構擦除,(3) |
[編輯] 示例
執行此程式碼
#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)
[編輯] 參閱
| (C++17) |
從另一個容器拼接節點 (公共成員函式) |
| 插入元素 或節點(C++17 起) (公共成員函式) | |
| 擦除元素 (公共成員函式) |