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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 32: Map and Unordered Map | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Associate keys with values – `set`, `map`, `unordered_set`, `unordered_map`
  • Ordered vs. hash containers
  • Custom key types and hashers
  • Element access methods (operator[], at, find)

Map and Unordered Map

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().


Example: std::map for counting word frequencies

std::map<std::string, int> freq;
std::string word;
while (std::cin >> word) {
    ++freq[word];
}
for (const auto& [w, c] : freq) {
    std::cout << w << \": \" << c << '\
';
}

Example: std::unordered_map with a custom key type

struct 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::emplace to 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.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 31: Set and Unordered SetContinue to lesson 33Lesson 33: Algorithms (sort, find, transform, etc.)Back to C++ Course curriculum