名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | multimap
 
 
 
 
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) 相同。此過載僅當限定 ID 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"}}
特性測試 標準 特性
__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::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)
從另一個容器拼接節點
(public member function) [edit]
插入元素 或節點(C++17 起)
(public member function) [edit]
擦除元素
(public member function) [edit]