Start learning free

LESSON 121 OF 667 · DICTIONARIES

Dictionaries (unordered_map) in C++

Lesson

In C++, an unordered_map works like a dictionary — it stores key-value pairs where each key maps to a value. Include <unordered_map> to use it.

unordered_map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 72;

The type parameters <string, int> specify the key type and value type. You can also initialize using an initializer list:

unordered_map<string, int> ages = {
    {"Alice", 25},
    {"Bob", 30}
};
cout << ages["Alice"];  // 25
cout << ages.size();    // 2

Assignment
Follow the Coding Tutorial and create an unordered_map named scores with three student scores!


Hint
Declare unordered_map<string, int> scores then use scores["Alice"] = 95 to add entries.

STEP 1 OF 2
    Ctrl + Enter to check