C++ ordered maps and frequencies

std::map stores unique keys in comparator order. Access with operator[] inserts a missing key with a value-initialized mapped value, which is zero for int.

C++
#include <iostream>
#include <map>
#include <string>
#include <cassert>
int main() {
    std::map<std::string, int> counts;
    for (const std::string word : {"red", "blue", "red"}) ++counts[word];
    for (const auto& entry : counts) {
        std::cout << entry.first << ' ' << entry.second << '\n';
    }
    assert(counts.find("green") == counts.end());
}
Read the full lesson