unordered_map: For faster average O(1) lookup (vs O(log n) for map), use unordered_map from <unordered_map>. It is not sorted but much faster for large datasets.
Exercise
Read a string of words from the user (space-separated) and count the frequency of each word using a map. Print the word frequency table.
Show Solution
#include <iostream>
#include <map>
#include <sstream>
using namespace std;
int main() {
string line, word;
cout << "Enter text: ";
getline(cin, line);
map<string, int> freq;
istringstream iss(line);
while (iss >> word) freq[word]++;
for (const auto& [w, c] : freq)
cout << w << ": " << c << endl;
return 0;
}
Quiz
What does map::count(key) return when the key exists?
A) The value associated with the key
B) 1
C) The number of duplicate keys
D) 0
Answer
B) 1 — since map keys are unique, count is always 0 or 1.
Summary
map<K,V> stores unique sorted key-value pairs.
Access: m[key] or m.at(key); search with find() or count().
Use unordered_map for O(1) average lookups without ordering.