unordered_map for
Counting
Learn how to use C++'s unordered_map to count frequencies, group elements, and solve real problems with hash-based key-value storage.
What Is a Key-Value Map?
A map stores pairs: every key is associated with a value. Think of a dictionary: the word is the key, and the definition is the value.
Why unordered_map?
C++ provides unordered_map in the <unordered_map> header. It uses a hash table internally, giving average \( O(1) \) lookup, insert, and delete: much faster than a sorted map's \( O(\log n) \).
The Counting Pattern
The most common use: count how many times each element appears. The key is the element, and the value is its frequency.
#include <unordered_map> #include <vector> #include <iostream> int main() { std::vector<std::string> fruits = {"apple", "banana", "apple", "cherry", "banana", "apple"}; std::unordered_map<std::string, int> freq; for (const auto& f : fruits) { freq[f]++; // auto-creates key with 0, then increments } for (const auto& [key, val] : freq) { std::cout << key << ": " << val << "\n"; } }
How operator[] Works
The bracket operator map[key] does two things depending on whether the key exists:
map vs unordered_map
| std::map | std::unordered_map | |
|---|---|---|
| Internal structure | Red-black tree | Hash table |
| Lookup time | \( O(\log n) \) | \( O(1) \) average |
| Iteration order | Sorted by key | Unordered |
| Key requirement | Must support < |
Must be hashable |
| Best for counting? | Slower | Faster (preferred) |
Essential Operations
map[key] returns a reference. Creates key with default value if missing.map.find(key) returns an iterator. Returns map.end() if not found.map.count(key) returns 1 if key exists, 0 otherwise.map.erase(key) removes the key-value pair.How to Apply the Pattern
#include <unordered_map>int.freq[element]++.freq[key], freq.count(key), or iterate to read results.Example 1: Character Frequency
Problem: Given a string, count how many times each character appears.
std::string s = "hello world"; std::unordered_map<char, int> freq; for (char c : s) { freq[c]++; } // freq['l'] == 3, freq['o'] == 2, freq[' '] == 1
Example 2: Most Frequent Element
Problem: Given a vector of integers, find the element that appears the most.
std::vector<int> nums = {4, 1, 2, 4, 2, 4, 3}; std::unordered_map<int, int> freq; for (int n : nums) freq[n]++; // Find the entry with the highest frequency int maxKey = 0; // A default value if nums is empty int maxVal = 0; for (const auto& [key, val] : freq) { if (val > maxVal) { maxVal = val; maxKey = key; } } // maxKey == 4, maxVal == 3
Example 3: Grouping by Property
Problem: Group words by their first letter.
std::vector<std::string> words = {"ant", "apple", "bat", "bee", "cat"}; std::unordered_map<char, std::vector<std::string>> groups; for (const auto& w : words) { groups[w[0]].push_back(w); } // groups['a'] == {"ant", "apple"} // groups['b'] == {"bat", "bee"} // groups['c'] == {"cat"}
Counting Step by Step
Tracing freq[x]++ on input ["a", "b", "a", "c", "a", "b"]:
Checking If a Key Exists
Sometimes you need to check before accessing. There are two safe ways:
// Method 1: count() if (freq.count("apple")) { std::cout << "apple count: " << freq["apple"]; } // Method 2: find() auto it = freq.find("banana"); if (it != freq.end()) { std::cout << "banana count: " << it->second; }
Iterating Over the Map
Two common styles for looping through all key-value pairs:
// C++17 structured bindings (preferred) for (const auto& [key, val] : freq) { std::cout << key << " -> " << val << "\n"; } // Classic iterator style for (auto it = freq.begin(); it != freq.end(); ++it) { std::cout << it->first << " -> " << it->second << "\n"; }
Common Mistakes
map[key] to check if a key exists: this silently creates the key with value 0. Use .count() or .find() instead.<unordered_map>. The compiler error may be confusing: "unordered_map is not a member of std".int, string, char have default hashes.Quick Reference Table
| Operation | Syntax | Time |
|---|---|---|
| Insert / Update | m[key] = val |
\( O(1) \) avg |
| Increment | m[key]++ |
\( O(1) \) avg |
| Check existence | m.count(key) |
\( O(1) \) avg |
| Find iterator | m.find(key) |
\( O(1) \) avg |
| Delete | m.erase(key) |
\( O(1) \) avg |
| Size | m.size() |
\( O(1) \) |
Question 1 of 5
What happens when you write freq["dog"]++ and the key "dog" does not exist in the map?
int, the default is 0. Then ++ increments it to 1.Question 2 of 5
Which method should you use to check if a key exists in an unordered_map without inserting it?
count(key) returns 1 if the key exists and 0 otherwise, without creating the key. Option A would silently insert the key. Option B throws if missing. Option D does not exist in C++.Question 3 of 5
What is the average time complexity of inserting a new key-value pair into an unordered_map?
Question 4 of 5
std::vector<int> v = {5, 3, 5, 7, 3, 5};
std::unordered_map<int, int> m;
for (int x : v) m[x]++;
std::cout << m.size();
What does the code above print?
m.size() returns 3.Question 5 of 5
You want to group a list of students by the first letter of their name. What should the value type of your unordered_map be?
vector<string> stores all the student names under each first-letter key. int would be for counting, not grouping.