C++: Read a required map key without inserting it
A lookup for required configuration should not silently add a default value. std::map::at returns the stored value or throws std::out_of_range when the key is absent.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. 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 as cpp-map-at-required-key.cpp:
#include <cassert>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
int main() {
const std::map<std::string, int> settings{{"workers", 3}};
std::cout << "workers: " << settings.at("workers") << '\n';
bool missing = false;
try {
(void)settings.at("retries");
} catch (const std::out_of_range&) {
missing = true;
std::cout << "retries: missing\n";
}
assert(missing && settings.size() == 1);
std::cout << "entries: " << settings.size() << '\n';
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-map-at-required-key.cpp -o cpp-map-at-required-key &&
./cpp-map-at-required-keyObserved output:
workers: 3
retries: missing
entries: 1How it works
The map is const, so this lookup also works through a read-only interface. The successful call returns a reference to the mapped integer. The example catches the missing-key exception and prints its own stable message instead of implementation-specific exception text.
Limits and choices
Use find when absence is an ordinary branch that needs no exception. operator[] on a mutable map inserts a missing key with a value-initialized mapped value; that behavior suits counters but can hide a missing setting. A reference returned by at cannot outlive its element or container.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-map-at-required-key.cpp cpp-map-at-required-key
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.