skip to content

In C++17, how do you change the key of an element already stored in a std::map or std::multimap, and what does extract save you?

level: seniorimportance: nice to knowfreq 25%

answer

  1. the key is const in value_type
  2. node handles
  3. nh.key() is writable
  4. relink, no reallocation
  5. merge moves nodes, not values

basics

~20 s

Stored keys are const, so extract the node, write nh.key(), and insert the node handle back. The element is never copied, moved or reallocated; only tree links change, and a pointer taken before extraction refers to the same element afterwards.

solid answer

~40 s

`std::map`'s `value_type` is `pair<const Key, T>`, so you cannot assign a new key through an iterator, and erase-then-insert would copy or move the value and free and allocate a node. C++17 node handles fix that: `auto nh = m.extract(it);` unlinks the node and transfers ownership to a `node_type`; `nh.key()` returns a **non-const** reference; `m.insert(std::move(nh))` links the same node back at its new position. No allocation, no copy or move of the element. `extract` invalidates only iterators to that element; pointers and references survive, though using them while the handle owns the node is undefined. `merge(source)` applies the same idea in bulk, splicing nodes from a compatible container and leaving duplicates behind in unique-key containers.

code

cpp · 20 lines
cpp
#include <iostream>
#include <map>
#include <set>
#include <string>

int main() {
    // resting orders keyed by price; several orders may share a price
    std::multimap<int, std::string> book{{10100, "o1"}, {10100, "o2"}, {10105, "o3"}};

    const std::string* addr = &book.find(10105)->second;
    auto nh = book.extract(book.find(10105));  // unlink the node, no deallocation
    nh.key() = 10101;                           // key is writable while the handle owns it
    auto pos = book.insert(std::move(nh));      // relink: no allocation, no copy
    std::cout << pos->first << ' ' << pos->second
              << " same node=" << (&pos->second == addr) << '\n';

    std::set<int> a{1, 2, 3}, b{3, 4};
    a.merge(b);  // node 4 moves into a; 3 stays in b (duplicate key)
    std::cout << "a=" << a.size() << " b=" << b.size() << " b has " << *b.begin() << '\n';
}

go deeper

for a junior

Know that keys inside std::map and std::set are const, so changing one means removing and re-inserting the element.

for a middle

Describe extract, nh.key() and insert(std::move(nh)) as the C++17 way to re-key without copying, and what insert returns for unique keys.

for a senior

Use node handles on hot paths such as order amendments, handle failed re-insertion, and state exactly which iterators, pointers and references survive.

for a principal

Judge when node-level operations justify a node-based container at all, versus a contiguous structure that re-sorts in bulk.

## Why you cannot just assign the key The ordered containers keep elements sorted by key, so a key changed in place would leave the element at the wrong position in the tree. The type system prevents it: for `std::map` and `std::multimap` the `value_type` is **`std::pair<const Key, T>`**, and for `std::set` and `std::multiset` every iterator is a constant iterator. `it->first = new_price;` does not compile. Before C++17 the only way to re-key was erase and re-insert: - copy or move the mapped value out, - `erase(it)`, which destroys the element and frees its node, - insert the new key and value, which allocates a fresh node and constructs the value again. For a large or non-movable mapped value, or a hot path in an order-matching engine, that is a real cost. ## Node handles C++17 (feature-test macro `__cpp_lib_node_extract`) gave the node-based containers a **node handle** type, `node_type`. It is a move-only object that owns exactly one element together with the allocator it was allocated from. - **`extract(position)`** removes the element at an iterator and returns a `node_type` owning it, in amortized constant time. **`extract(key)`** does the same for the first element with an equivalent key, or returns an empty handle. - **`nh.key()`** returns a **non-const** `key_type&`, and `nh.mapped()` the value (for maps); `nh.value()` returns the element for sets. `nh.empty()` and `explicit operator bool` test ownership. - **`insert(std::move(nh))`** links the node back. For unique-key containers it returns `insert_return_type` with members `position`, `inserted` and `node`; if an equivalent key already exists, the insertion fails and **`node` hands the element back** to you. For `std::multimap` and `std::multiset` it returns an `iterator`, since insertion always succeeds. - A handle that is destroyed while still owning a node destroys the element and frees the node, just like an erase. The standard's invalidation rule is precise: `extract` invalidates only iterators to the removed element; pointers and references to it remain valid, but **accessing the element through them while a `node_type` owns it is undefined behaviour**. After a successful re-insertion they are usable again. The snippet below compares a pointer taken before extraction with the address after re-insertion and prints `same node=1`. ## Re-pricing a resting order An order book stores resting orders in a `std::multimap<int, Order>` keyed by price. When a trader amends an order's price: 1. `auto nh = book.extract(it);` takes the order out of the tree without touching the `Order` object. 2. `nh.key() = new_price;` rewrites the key in the handle. 3. `book.insert(std::move(nh));` links it at the new price level. For a `std::multimap` the element goes after existing orders at that price, which happens to match time priority for an amendment that loses its place. If the book is a unique-key `std::map` and the new key is taken, check `inserted` and handle `node` explicitly; otherwise the element is destroyed with the returned handle. ## merge: splicing whole containers `a.merge(b)` attempts to extract each element of `b` and insert it into `a` using `a`'s comparator. For unique-key targets, elements whose key already exists in `a` **stay in `b`**. No element is copied or moved; pointers and references to transferred elements now refer to members of `a`, and iterators to them behave as iterators into `a`. Handles and `merge` work between containers with **compatible nodes**: | Source | Compatible targets | |---|---| | `map<K, T, C1, A>` | `map<K, T, C2, A>`, `multimap<K, T, C2, A>` | | `set<K, C1, A>` | `set<K, C2, A>`, `multiset<K, C2, A>` | The comparator may differ; the key, mapped type and allocator type must match, and the allocators must compare equal (a precondition, not a check). ## Rules worth knowing - Node handles are **move-only**; they cannot be copied. - Extracting from a `std::map` and inserting into a `std::multimap` (or back) is allowed and is how you change a container's uniqueness policy without reallocating. - The unordered containers have the same API with their own compatibility rows; `std::flat_map` has no node handles at all, because it has no nodes. - Use node handles to move **non-movable** mapped values between containers: the element object itself never moves. - Re-keying through a handle still costs a logarithmic re-insertion plus rebalancing (extracting by iterator is amortized constant); what it removes is the allocation, the deallocation and the element's copy or move.

  • What happens if you re-insert an extracted node into a std::map that already holds an equivalent key?
    Insertion fails: the returned `insert_return_type` has `inserted == false`, `position` pointing at the existing element, and `node` holding your element again. If you ignore that result and let it go out of scope, the handle destroys your element. Check `inserted`, then decide whether to merge values, pick another key or keep the node.
  • Why can a node handle move a mapped type that is neither copyable nor movable between two maps?
    The handle owns the node that contains the element, so transferring it just relinks that node into another tree. The element object stays at the same address and is never copied or moved. That is something `erase` plus `emplace` can never do for such a type, because it would have to construct the value again.

  • You can change a std::map key through it->first if you re-sort afterwards
  • extract copies the element into the node handle
  • merge moves every element of the source, duplicates included
  • Node handles only work between maps with identical comparators
  • Using a pointer to the element while the handle owns it is safe