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.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
