Walk a sequence and count occurrences of each value in a hash map. Classic "get current count, add one, write back" loop.

Algorithm

Canonical input ["fig", "apple", "fig", "pear", "apple", "fig"] produces the final map {fig: 3, apple: 2, pear: 1}.

Basic Implementation

basic.cpp
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

int main() {
    std::vector<std::string> words = {"fig", "apple", "fig", "pear", "apple", "fig"};
    std::unordered_map<std::string, int> count;
    std::vector<std::string> seen;
    for (const std::string& word : words) {
        if (count.find(word) == count.end()) {
            seen.push_back(word);
        }
        count[word] = count[word] + 1;
    }
    std::cout << "{";
    for (size_t i = 0; i < seen.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << seen[i] << ": " << count[seen[i]];
    }
    std::cout << "}" << std::endl;
    return 0;
}

Complexity

  • Time: O(n) average
  • Space: O(k) where k is the number of distinct keys

Implementation notes

  • C++: std::unordered_map<std::string, int> is the canonical hash table. Indexing with count[word] default-initialises to 0, which is exactly the "get current count" half of the lesson.
  • The seen vector keeps the lesson's first-seen iteration order honest; std::unordered_map deliberately does not promise insertion order, and the lesson should not pretend otherwise.
  • The replay renders the map as a list of key/value rows in first-seen order and animates the count increment on each frame.
get-or-default `count[word]` returns the current count or default-initialises to `0`. Adding one in place is the canonical pattern.
first-seen order A small `std::vector<std::string> seen` records each key the first time it appears so the final printout is deterministic without exposing the hash-map's bucket order.