C++ Basics: Rename a Map Key Without Losing a Rejected Node
Use a node handle to rename a key and recover safely when the destination already exists.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and its standard-library headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as map-node-key-rename-demo.cpp:
#include <iostream>
#include <map>
#include <string>
#include <utility>
int main() {
std::map<std::string, int> quotas{{"alpha", 3}, {"beta", 9}};
auto node = quotas.extract("alpha");
if (node.empty()) {
std::cerr << "Missing source key\n";
return 1;
}
node.key() = "beta";
auto attempted = quotas.insert(std::move(node));
std::cout << std::boolalpha
<< "Renamed to beta: " << attempted.inserted << '\n';
if (!attempted.inserted) {
attempted.node.key() = "gamma";
const auto recovered = quotas.insert(std::move(attempted.node));
std::cout << "Recovered as gamma: " << recovered.inserted << '\n';
}
for (const auto& [name, quota] : quotas) {
std::cout << name << ": " << quota << '\n';
}
}Compile and run it. The second command runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic map-node-key-rename-demo.cpp -o map-node-key-rename-demo &&
./map-node-key-rename-demoObserved output:
Renamed to beta: false
Recovered as gamma: true
beta: 9
gamma: 3Read the result
The beta collision leaves the existing value intact. The returned node still owns the extracted alpha entry; assigning gamma gives it a free destination.
Apply it carefully
Check extraction before accessing the handle. A rejected insert returns ownership in the result node. Ignoring that node can discard the entry. Use compatible allocators when moving nodes between containers.
The C++ working draft documents the relevant container rules. This example uses only features available in C++20, even though the linked draft also includes newer additions.
Clean up
Remove only the source and executable created here, then remove the empty practice directory:
rm -- map-node-key-rename-demo.cpp map-node-key-rename-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.