Topic 91 of 91 11. Additional C++ Topics Added Interactive Tutorial

unordered_map and unordered_set in C++: Hash-Based Collections

10 mins read Last updated: 26 Sep 2026 20,467 views

Direct Answer & Core Concept

std::unordered_map and std::unordered_set are hash-table containers defined in and . They provide average $O(1)$ constant time complexity for insertions, lookups, and deletions by computing hash buckets via std::hash, compared to $O(\log N)$ in tree-based std::map/std::set.

Detailed Explanation & Mechanics

1. Hash Table Architecture:

Architecture Diagram
Key: "user:101" ──► std::hash ──► Hash Code % BucketCount ──► Bucket Index [3]
                                                                     │
                                                       ┌─────────────┴─────────────┐
                                                       ▼                           ▼
                                               [ "user:101", Data ] ──► [ Collided Node ]

2. Comparison: Map vs Unordered Map:

Architecture Diagram
┌─────────────────────┬───────────────────────────┬───────────────────────────┐
│ Feature             │ std::map / std::set       │ std::unordered_map / set  │
├─────────────────────┼───────────────────────────┼───────────────────────────┤
│ Data Structure      │ Red-Black Tree (Balanced) │ Hash Table (Buckets)      │
│ Element Ordering    │ Strictly Sorted           │ Unordered / Arbitrary     │
│ Average Lookup Time │ O(log N)                  │ O(1)                      │
│ Worst-case Lookup   │ O(log N)                  │ O(N) (Hash Collisions)    │
│ Key Requirements    │ operator<                 │ std::hash and operator==  │
└─────────────────────┴───────────────────────────┴───────────────────────────┘

Runnable Code Example: unordered_map and unordered_set in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>

int main() {
    // 1. std::unordered_map (O(1) Hash Map)
    std::unordered_map<std::string, double> productPrices = {
        {"Keyboard", 79.99},
        {"Monitor", 249.50},
        {"Mouse", 39.99}
    };

    // Fast O(1) average lookup
    std::string query = "Monitor";
    if (productPrices.find(query) != productPrices.end()) {
        std::cout << "[Lookup] " << query << " costs $" << productPrices[query] << "\n";
    }

    // 2. std::unordered_set (O(1) Hash Set)
    std::unordered_set<std::string> blacklistedIPs = {
        "192.168.1.100", "10.0.0.50", "172.16.0.22"
    };

    std::string testIP = "10.0.0.50";
    if (blacklistedIPs.count(testIP)) {
        std::cout << "[Security Alert] IP " << testIP << " is BLACKLISTED!\n";
    }
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What causes worst-case $O(N)$ lookup in `std::unordered_map`?

A: Severe hash collisions where many keys hash to the same bucket index, turning bucket lookup into a linear search down a linked list chain.
Q

Q: What two things must you provide to use a custom class as a key in `std::unordered_map`?

A: 1) A specialization of `std::hash` to compute hash codes. 2) An overloaded `operator==` to check for key equality.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Use std::unordered_map when maximum lookup performance ($O(1)$) is needed and ordering does not matter.
• Call .reserve(expectedCount) on unordered containers to pre-allocate hash buckets and avoid costly rehashing.
• Use std::map when you need sorted keys or range queries (lower_bound / upper_bound).
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.