C++ Basics: Look Up Unordered Map Keys Without Inserting Them
Reading a missing key with operator[] can silently add it to an unordered map. Use find when the lookup must leave the map unchanged.
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, and make g++ available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. 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 unordered-map-find-demo.cpp:
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
const std::unordered_map<std::string, int> ports{{"web", 8080}};
for (const std::string service : {"web", "metrics"}) {
const auto found = ports.find(service);
if (found == ports.end()) {
std::cout << service << ": missing\n";
} else {
std::cout << service << ": " << found->second << '\n';
}
}
std::cout << "Entries: " << ports.size() << '\n';
}Compile and run it. The && prevents execution if compilation fails:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic unordered-map-find-demo.cpp -o unordered-map-find-demo &&
./unordered-map-find-demoObserved output:
web: 8080
metrics: missing
Entries: 1Read the result
The web key returns its stored port. The missing metrics key produces end(), so the code reports absence without dereferencing that iterator. The final size remains one. Declaring the map const also prevents accidental insertion through operator[].
Apply it carefully
Check against end() before dereferencing the result. Unordered maps do not provide sorted iteration order; this output is deterministic because it follows a separate fixed list of lookup keys. In a mutable map, an insertion that rehashes invalidates iterators, so do not retain a lookup iterator across such changes.
The C++ working draft documents the relevant container behavior. The example uses only features available in C++20, even though the linked draft may include later additions.
Clean up
Remove only the source and executable created here, then remove the empty practice directory:
rm -- unordered-map-find-demo.cpp unordered-map-find-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.