Functions and collections · Lesson 10 of 21
map, set and unordered_map
Look things up by key, count occurrences, and drop duplicates.
10 minutes2 games
std::map stores key → value pairs, like a Python dict or a JavaScript object, always sorted by key. std::set is a collection of unique values, also sorted.
C++
#include <iostream>
#include <map>
#include <set>
#include <string>
int main() {
std::map<std::string, int> xp;
xp["Laila"] = 320;
xp["Karim"] = 150;
xp["Omar"] += 90; // missing key: created as 0, then += 90
for (const auto& entry : xp) {
std::cout << entry.first << ": " << entry.second << "\n";
}
std::cout << "has Nour? " << xp.count("Nour") << "\n";
std::set<std::string> cities = {"Cairo", "Giza", "Cairo", "Alexandria"};
std::cout << cities.size() << " unique cities, first " << *cities.begin() << "\n";
return 0;
}| std::map | std::unordered_map | |
|---|---|---|
Storage | balanced tree | hash table |
Order | sorted by key | no order |
Lookup | O(log n) | O(1) average |
When? | need order or ranges | just need speed |
C++
#include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
int main() {
std::string text = "to be or not to be";
std::unordered_map<std::string, int> counts;
std::istringstream words(text);
std::string w;
while (words >> w) counts[w]++;
std::cout << "to: " << counts["to"] << ", be: " << counts["be"] << ", or: " << counts["or"] << "\n";
std::cout << counts.size() << " different words\n";
return 0;
}What's the output?
#include <iostream>
#include <map>
int main() {
std::map<int, char> m = {{3, 'c'}, {1, 'a'}, {2, 'b'}};
m[1] = 'z';
for (const auto& p : m) std::cout << p.second;
std::cout << m.size() << "\n";
}What will this code print?
Exercise
Print each letter of "banana" with its count, alphabetically, one per line as a 3.
Expected output:
a 3 b 1 n 2
C++
#include <iostream>
#include <map>
#include <string>
int main() {
std::string word = "banana";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.