C++ Basics: Read Every Value for a Repeated Map Key
Use std::multimap::equal_range to read a whole group of entries sharing a key. A single find result cannot represent every matching record.
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 multimap-equal-range-group-demo.cpp:
#include <iostream>
#include <map>
#include <string>
int main()
{
std::multimap<std::string, int> jobs;
jobs.emplace("build", 101);
jobs.emplace("test", 201);
jobs.emplace("build", 102);
auto [first, last] = jobs.equal_range("build");
std::cout << "build jobs:";
for (auto it = first; it != last; ++it) std::cout << ' ' << it->second;
std::cout << '\n';
auto [missing_first, missing_last] = jobs.equal_range("deploy");
std::cout << "missing is empty: " << (missing_first == missing_last) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic multimap-equal-range-group-demo.cpp -o multimap-equal-range-group-demo &&
./multimap-equal-range-group-demoObserved output:
build jobs: 101 102
missing is empty: 1Read the result
Both build jobs are visited. The unhinted insertions retain their relative order within the equivalent-key group. The absent deploy key produces an empty iterator range.
Apply it carefully
Iterate over the half-open range: last marks the boundary and must not be dereferenced as a matching entry. The group is defined by comparator equivalence, not necessarily operator==. Use the member equal_range so the tree can locate boundaries directly. If erasing during traversal, use the iterator returned by erase rather than incrementing an invalidated iterator. Other non-erased multimap iterators remain valid.
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 -- multimap-equal-range-group-demo.cpp multimap-equal-range-group-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.