In C++17, std::unordered_map::extract()takes a pair out of the unordered_map without destroying it. It returns a node handle, a small object that owns the pair.
With the handle you can read key() and mapped(), change the key (normally impossible because keys are const), and then insert the node into the same or another map. No copy of the key or value is made. Include <unordered_map> and use -std=c++17 or newer.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Extract by key or by iterator. The result is a node handle.
C++
auto nh = m.extract(2); // by key
auto nh2 = m.extract(m.begin()); // by iterator
if (!nh.empty()) {
nh.key(); // the key (can be assigned)
nh.mapped(); // the value
}
Call
What it does
m.extract(key)
Removes the pair with that key and returns its node handle. If the key is missing, the returned handle is empty.
m.extract(pos)
Removes the pair that pos points to and returns its node handle.
nh.empty()
Tells you if the node handle holds nothing, for example after a failed extract(key).
Inside a node handle you can write nh.key() = newKey. After that, give the handle back with m.insert(std::move(nh)) to store the pair under its new key.