Is there a dictionary in C++? Not as a class with that name. The standard library does provide two containers that work like a dictionary in C++: std::map and std::unordered_map. Both store pairs of keys and values, and you find a value by its key instead of by its position. This guide uses std::map for the examples, because its entries are sorted and easy to reason about, and then explains when std::unordered_map is the better fit.
Include the headers
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
<map> provides std::map, <string> provides std::string, and <stdexcept> provides std::out_of_range, which at() throws when a key is missing.
Create a map
std::map<std::string, int> ages;
The first type is the key type and the second is the value type. This map uses a name as the key and an age as the value. A new map starts out empty.
Add and update entries
ages["Alice"] = 30; // adds Alice, or changes her age if she is already in the map
ages["Bob"] = 25;
ages.emplace("Carol", 41); // adds Carol only if the key is not already there
Assigning with [] adds the key when it is missing and overwrites the value when it exists. emplace adds an entry only when the key is new, so it leaves an existing value unchanged.
Look up a value
There are three common ways to read a value. They behave differently when the key is missing.
ages["Alice"]returns the value. If the key is missing, it first inserts the key with a default value. For anint, that default is0.ages.at("Alice")returns the value, and throwsstd::out_of_rangeif the key is missing.ages.find("Alice")returns an iterator. If the key is missing, the iterator equalsages.end().
Use find when a missing key is a normal case:
auto it = ages.find("Dave");
if (it != ages.end()) {
std::cout << it->second << '\n';
} else {
std::cout << "Dave is not in the map\n";
}
Use at when a missing key should count as an error:
try {
std::cout << ages.at("Zed") << '\n';
} catch (const std::out_of_range&) {
std::cout << "No entry for Zed\n";
}
To check whether a key exists without reading its value, use count, which returns 0 or 1 for a std::map. Since C++20, contains returns a bool directly:
if (ages.contains("Bob")) {
std::cout << "Bob is in the map\n";
}
Remove an entry
ages.erase("Bob");
erase removes the entry with that key and returns how many entries it removed: 1 if the key existed, or 0 if it did not.
Erasing inside a range-based for loop leaves the loop holding an iterator that no longer points to a valid entry. When you need to remove entries while you loop, use an explicit iterator and take the one that erase returns:
for (auto it = ages.begin(); it != ages.end(); ) {
if (it->second < 30) {
it = ages.erase(it);
} else {
++it;
}
}
Loop over every entry
for (const auto& [name, age] : ages) {
std::cout << name << ": " << age << '\n';
}
Each element is a pair, and the structured binding splits it into name (the key) and age (the value). Structured bindings need C++17 or later.
A std::map visits its entries in key order, so “Alice” comes before “Carol”. By default, keys are compared with std::less, which uses <.
A complete example
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
ages.emplace("Carol", 41);
std::cout << ages["Alice"] << '\n';
auto it = ages.find("Dave");
if (it != ages.end()) {
std::cout << it->second << '\n';
} else {
std::cout << "Dave is not in the map\n";
}
ages.erase("Bob");
for (const auto& [name, age] : ages) {
std::cout << name << ": " << age << '\n';
}
}
Compile it with g++ -std=c++17 -Wall -Wextra main.cpp -o dictionary_demo, then run ./dictionary_demo. The output is:
30
Dave is not in the map
Alice: 30
Carol: 41
std::map or std::unordered_map?
Both containers store key-value pairs, but they differ in a few ways:
std::map |
std::unordered_map |
|
|---|---|---|
| Header | <map> |
<unordered_map> |
| Entry order | Sorted by key | No defined order |
| Lookup, insert and erase | Logarithmic in the number of entries | Average constant time |
| Key requirement | Keys can be compared with < |
Keys need a hash function |
The standard library provides hash functions for types such as std::string and the built-in numeric types. A custom key type needs its own hash function before you can use it with std::unordered_map.
Use std::map when you want entries in key order, or when your keys can be compared but have no hash function. Use std::unordered_map when you mostly need fast lookups and the order of entries does not matter.
Switching containers is often a small change. Replace std::map with std::unordered_map and <map> with <unordered_map>, and the calls in the examples above still compile. The loop then prints the entries in an order that is not defined, so the output may differ.
Plain C has no built-in dictionary
The C language has no standard dictionary, map or hash table type. If you are writing plain C, you can build a hash table from arrays, structs and pointers, or use a small third-party library. The code in this guide needs a C++ compiler.
Common mistakes
- Using
[]to check whether a key exists. It inserts the key with a default value when the key is missing. Usefind,countorcontainsinstead. - Calling
at()without handling a missing key. It throwsstd::out_of_range. - Expecting an order from
std::unordered_map. Its iteration order is not defined, and it can change as the map grows. - Erasing inside a range-based
forloop. Use the iterator thaterasereturns, as shown above.
Summary
In C++, a dictionary is usually a std::map or a std::unordered_map. Use [] to write values and to read values you know are present, find or contains to check for keys, and erase to remove them. Loop over entries with a range-based for and structured bindings. Choose std::map when you want sorted keys, and std::unordered_map when fast lookups matter more than order.