01 / 21

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.

C++

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.

Key Value "apple" 3 "banana" 1 "cherry" 5

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) \).

Average Speed
\( O(1) \) per operation: insert, find, erase, and access by key.
Unsorted Order
Keys are not in any particular order: iteration order is unpredictable.
Unique Keys
Each key can appear at most once. Inserting again overwrites the value.

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[key] Key exists? Yes Return ref No Insert key value = 0 Return ref Then ++ increments it

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

Access
map[key] returns a reference. Creates key with default value if missing.
Find
map.find(key) returns an iterator. Returns map.end() if not found.
Count
map.count(key) returns 1 if key exists, 0 otherwise.
Erase
map.erase(key) removes the key-value pair.

How to Apply the Pattern

1
Include the header: #include <unordered_map>
2
Declare the map: decide the key type (what you count) and set the value type to int.
3
Loop through data: for each element, do freq[element]++.
4
Query the map: use freq[key], freq.count(key), or iterate to read results.
5
Solve the problem: find the max frequency, filter by count, or group by key.

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"]:

Step Element Action Map State 1 "a" create a=0, then ++ {a:1} 2 "b" create b=0, then ++ {a:1, b:1} 3 "a" a exists, just ++ {a:2, b:1} 4 "c" create c=0, then ++ {a:2, b:1, c:1} 5 "a" a exists, just ++ {a:3, b:1, c:1} 6 "b" b exists, just ++ {a:3, b:2, c:1} Final: a=3, b=2, c=1

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

✕ Accidental Insertion
Using map[key] to check if a key exists: this silently creates the key with value 0. Use .count() or .find() instead.
✕ Forgetting the Header
Not including <unordered_map>. The compiler error may be confusing: "unordered_map is not a member of std".
✕ Custom Key Types
Using a struct or class as a key without providing a hash function. Only built-in types like 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?

Question 2 of 5

Which method should you use to check if a key exists in an unordered_map without inserting it?

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

What does the code above print?

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?