Lesson 32 of 45
C++Lesson 32: Map and Unordered Map
12 min
Course progress71%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 32 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
std::map associates keys with values in a sorted order (red‑black tree). std::unordered_map provides average O(1) lookup using a hash table. Both support operator[], at(), find(), insert(), and erase().
std::map for counting word frequenciesstd::map<std::string, int> freq;
std::string word;
while (std::cin >> word) {
++freq[word];
}
for (const auto& [w, c] : freq) {
std::cout << w << \": \" << c << '\
';
}
std::unordered_map with a custom key typestruct Key {
int id;
std::string tag;
};
struct KeyHash {
std::size_t operator()(const Key& k) const noexcept {
return std::hash<int>{}(k.id) ^ (std::hash<std::string>{}(k.tag) << 1);
}
};
struct KeyEq {
bool operator()(const Key& a, const Key& b) const noexcept {
return a.id == b.id && a.tag == b.tag;
}
};
std::unordered_map<Key, double, KeyHash, KeyEq> data;
data[{1, \"alpha\"}] = 3.14;
std::cout << \"Value: \" << data.at({1, \"alpha\"}) << '\
';
Tip: Use
map::emplaceto construct elements in‑place and avoid unnecessary copies.
<Alert type="warning">Do not use operator[] on a const map; it will insert a default‑constructed value if the key does not exist. Use find or at instead.