C++ · Module 13 · Lesson 41 min read

Hash Containers: unordered_map & unordered_set

std::unordered_map / std::unordered_set

Same interface as map/set ([], at, find, contains, insert, erase, count), but:

map / setunordered_map / unordered_set
Structurebalanced treehash table
Lookup/insertO(log n)O(1) average, O(n) worst
Iteration ordersortedunspecified (looks random)
Key needs<std::hash + ==

How hashing works

  1. std::hash<Key> turns the key into a number
  2. That number picks a bucket
  3. Keys in the same bucket (collisions) are compared with == When too full (load factor > max_load_factor(), default 1.0), the table rehashes into more buckets.

Performance tips

  • reserve(n) when you know the approximate size — avoids repeated rehashing
  • A bad hash function (many collisions) makes it O(n)

Using your own type as a key

Provide equality and a hash:

c
struct Point { int x, y; bool operator==(const Point&) const = default; };
struct PointHash {
    std::size_t operator()(const Point& p) const {
        return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
    }
};
std::unordered_map<Point, std::string, PointHash> places;

Or specialize std::hash<Point>.

When to use which ✅

  • Need sorted output, ranges, lower_bound → map/set
  • Just need fast lookup/counting → unordered_map/unordered_set
  • Very small collections → a vector with linear search can be fastest

Classic uses

Word/frequency counting, caching results (memoization), "have I seen this?" checks, grouping by key, two-sum style problems.

Example

C++
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

struct Point {
    int x, y;
    bool operator==(const Point&) const = default;
};
struct PointHash {
    std::size_t operator()(const Point& p) const {
        return std::hash<int>{}(p.x) * 31 + std::hash<int>{}(p.y);
    }
};

int main() {
    std::string text = "save more spend less save daily spend wisely save";
    std::unordered_map<std::string, int> freq;
    std::istringstream in(text);
    for (std::string w; in >> w;) ++freq[w];                     // O(1) average per word

    std::vector<std::pair<std::string, int>> sorted(freq.begin(), freq.end());
    std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) {
        return a.second != b.second ? a.second > b.second : a.first < b.first;
    });
    std::cout << "word counts (sorted for display):\n";
    for (const auto& [w, c] : sorted) std::cout << "  " << w << ": " << c << '\n';

    // first repeated transaction ID
    std::vector<int> ids = { 101, 205, 333, 205, 101 };
    std::unordered_set<int> seen;
    for (int id : ids) {
        if (!seen.insert(id).second) { std::cout << "first duplicate id: " << id << '\n'; break; }
    }

    // two-sum: which two bills add up to 2000?
    std::vector<int> bills = { 450, 1200, 300, 800, 1550 };
    std::unordered_map<int, int> index_of;
    for (int i = 0; i < static_cast<int>(bills.size()); ++i) {
        if (auto it = index_of.find(2000 - bills[i]); it != index_of.end()) {
            std::cout << "bills " << bills[it->second] << " + " << bills[i] << " = 2000\n";
            break;
        }
        index_of[bills[i]] = i;
    }

    std::unordered_map<Point, std::string, PointHash> map_pins;
    map_pins[{ 28, 84 }] = "Pokhara";
    map_pins[{ 27, 85 }] = "Kathmandu";
    std::cout << "pin at (27, 85): " << map_pins.at({ 27, 85 }) << '\n';

    std::unordered_map<int, int> big;
    big.reserve(1000);
    std::cout << "buckets after reserve(1000): at least " << (big.bucket_count() >= 1000 ? 1000 : 0)
              << ", max load factor " << big.max_load_factor() << '\n';
    return 0;
}

/* Output:
word counts (sorted for display):
  save: 3
  spend: 2
  daily: 1
  less: 1
  more: 1
  wisely: 1
first duplicate id: 205
bills 1200 + 800 = 2000
pin at (27, 85): Kathmandu
buckets after reserve(1000): at least 1000, max load factor 1
*/