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

  1. Unlinks the node that contains the element pointed to by position and returns a node handle that owns it.

# Declarations

node_type extract( const_iterator position );

(since C++17)

node_type extract( const Key& k );

(since C++17)

template< class K >
node_type extract( K&& x );

(since C++23)

# Parameters

# Return value

A node handle that owns the extracted element, or empty node handle in case the element is not found in (2,3).

# Notes

extract is the only way to change a key of a map element without reallocation:

# Example

#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);
}

# See also