C++ Map
A std::map stores key–value pairs. You look up a value by its key — a word to its definition, a username to an account, a product code to a price. Keys are unique and kept in sorted order. Include <map>.
Creating and using a map
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages = {
{"Mira", 31},
{"Jon", 25}
};
ages["Lena"] = 42; // insert a new key
ages["Jon"] = 26; // update an existing key
cout << "Jon is " << ages["Jon"] << "\n";
cout << "size: " << ages.size() << "\n";
for (const auto& [name, age] : ages) { // sorted by key
cout << name << ": " << age << "\n";
}
}Jon is 26
size: 3
Jon: 26
Lena: 42
Mira: 31
Each element is a std::pair<const Key, Value>, with members .first (key) and .second (value). Structured bindings — auto [name, age] — unpack it nicely.
The [] trap
map[key] inserts the key with a default value if it does not exist yet. That is convenient for counting, but surprising when you only meant to look something up:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, double> prices = {{"apple", 0.5}, {"pear", 0.75}};
cout << prices["mango"] << "\n"; // oops: inserts mango = 0
cout << "size now " << prices.size() << "\n";
// safe lookups
cout << boolalpha << prices.contains("kiwi") << "\n"; // C++20
if (auto it = prices.find("pear"); it != prices.end()) {
cout << it->first << " costs " << it->second << "\n";
}
try {
cout << prices.at("kiwi") << "\n"; // at() throws if missing
} catch (const out_of_range&) {
cout << "no kiwi\n";
}
}0
size now 3
false
pear costs 0.75
no kiwi
| Lookup | Missing key |
|---|---|
m[key] |
inserts a default value (not allowed on a const map) |
m.at(key) |
throws std::out_of_range |
m.find(key) |
returns m.end() |
m.contains(key) |
returns false |
m.count(key) |
returns 0 |
Counting with a map
The insert-on-access behaviour of [] makes frequency counting a one-liner:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
string text = "mississippi";
map<char, int> freq;
for (char c : text) {
freq[c]++; // missing keys start at 0
}
for (const auto& [ch, n] : freq) {
cout << ch << ": " << string(n, '#') << " " << n << "\n";
}
}i: #### 4
m: # 1
p: ## 2
s: #### 4
Inserting, erasing and grouping
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int main() {
map<string, vector<string>> byDept;
struct Emp { string name, dept; };
vector<Emp> staff = {
{"Ava", "Sales"}, {"Raj", "IT"}, {"Zoe", "Sales"}, {"Tim", "HR"}, {"Kim", "IT"}
};
for (const auto& e : staff) {
byDept[e.dept].push_back(e.name);
}
auto [it, ok] = byDept.insert({"IT", {}}); // key exists: no change
cout << "inserted IT again? " << boolalpha << ok << "\n";
byDept.erase("HR");
for (const auto& [dept, names] : byDept) {
cout << dept << ":";
for (const auto& n : names) cout << " " << n;
cout << "\n";
}
}inserted IT again? false
IT: Raj Kim
Sales: Ava Zoe
Related containers
| Container | Header | Ordered by key? | Duplicate keys? | Lookup |
|---|---|---|---|---|
std::map |
<map> |
yes | no | O(log n) |
std::multimap |
<map> |
yes | yes | O(log n) |
std::unordered_map |
<unordered_map> |
no | no | O(1) average |
Tip:
unordered_mapis the go-to choice for fast lookups when order doesn't matter. Usemapwhen you need the keys sorted, or range queries withlower_bound/upper_bound.
Test yourself
What happens when you read m["x"] and the key "x" does not exist?
- An exception is thrown
- It returns end()
- The key is inserted with a default value
- Compile error
In what order does a range-based loop visit a std::map?
- Insertion order
- Sorted by key
- Sorted by value
- Random
Which lookup throws std::out_of_range for a missing key?
- m[key]
- m.find(key)
- m.at(key)
- m.count(key)