Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 26 of 45 · C++

Lesson 32: Map and Unordered Map

Duration: 12 min

Map and Unordered Map\n\nstd::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.

Previous: Lesson 31: Set and Unordered SetNext: Lesson 33: Algorithms (sort, find, transform, etc.)