Lesson 26 of 45 · C++
Lesson 32: Map and Unordered Map
Duration: 12 min
Lesson 26 of 45 · C++
Duration: 12 min
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().\n\n---\n\n## Example: std::map for counting word frequencies\ncpp\nstd::map<std::string, int> freq;\nstd::string word;\nwhile (std::cin >> word) {\n ++freq[word];\n}\nfor (const auto& [w, c] : freq) {\n std::cout << w << \": \" << c << '\\n';\n}\n\n\n## Example: std::unordered_map with a custom key type\ncpp\nstruct Key {\n int id;\n std::string tag;\n};\nstruct KeyHash {\n std::size_t operator()(const Key& k) const noexcept {\n return std::hash<int>{}(k.id) ^ (std::hash<std::string>{}(k.tag) << 1);\n }\n};\nstruct KeyEq {\n bool operator()(const Key& a, const Key& b) const noexcept {\n return a.id == b.id && a.tag == b.tag;\n }\n};\nstd::unordered_map<Key, double, KeyHash, KeyEq> data;\ndata[{1, \"alpha\"}] = 3.14;\nstd::cout << \"Value: \" << data.at({1, \"alpha\"}) << '\\n';\n\n\n> Tip: Use map::emplace to construct elements in‑place and avoid unnecessary copies.\n\n---\n\n<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.