C++ Basics: Update a Map Entry and Detect New Keys
Use std::map::insert_or_assign when an incoming value should replace an existing value or create a new entry.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus 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-insert-or-assign-result-demo.cpp:
#include <iostream>
#include <map>
#include <string>
int main()
{
std::map<std::string, int> stock{{"bolts", 5}};
auto updated = stock.insert_or_assign("bolts", 8);
auto added = stock.insert_or_assign("nuts", 12);
std::cout << std::boolalpha;
std::cout << "bolts inserted: " << updated.second
<< ", value: " << updated.first->second << '\n';
std::cout << "nuts inserted: " << added.second
<< ", value: " << added.first->second << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic map-insert-or-assign-result-demo.cpp -o map-insert-or-assign-result-demo &&
./map-insert-or-assign-result-demoObserved output:
bolts inserted: false, value: 8
nuts inserted: true, value: 12Read the result
The bolts entry is assigned a new value, so its inserted flag is false. Nuts is a new key, so its flag is true. Both returned iterators identify the resulting entries.
Apply it carefully
The boolean means insertion, not operation success: false is the normal result for assignment. Unlike try_emplace, this operation deliberately overwrites an existing mapped value. The supplied value expression is evaluated before the function call, even if the key already exists. Map insertion preserves existing iterators, but the mapped value of an updated entry has changed; consider that if other code retains a reference to it.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- map-insert-or-assign-result-demo.cpp map-insert-or-assign-result-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.