Skip to main content

Lesson 2 of 7

Associative Containers - set, map & unordered_map

`std::set` and `std::map` are **ordered** containers backed by a red-black tree - O(log n) lookup, insert, and erase, with elements always sorted. `std::unordered_map` uses a **hash table** - amortised O(1) average case for all operations, but O(n) worst case (hash collisions). Prefer `unordered_map` for performance when you don't need ordering; use `map` when you need sorted iteration or range queries.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

set, map, unordered_map - Complete API & Custom Keys

set, map, unordered_map - Complete API & Custom Keys
#include <iostream>
#include <set>
#include <map>
#include <unordered_map>
#include <string>
#include <functional>  // std::hash

// ── Custom key - needs operator< for map/set ─────────────────
struct Person {
    std::string name;
    int         age;
    bool operator<(const Person& o) const {
        return name < o.name || (name == o.name && age < o.age);
    }
};

// ── Custom hash for unordered_map ─────────────────────────────
struct PersonHash {
    size_t operator()(const Person& p) const {
        size_t h1 = std::hash<std::string>{}(p.name);
        size_t h2 = std::hash<int>{}(p.age);
        return h1 ^ (h2 << 1);   // combine hashes
    }
};
struct PersonEqual {
    bool operator()(const Person& a, const Person& b) const {
        return a.name == b.name && a.age == b.age;
    }
};

int main() {
    // ── set ───────────────────────────────────────────────────
    std::set<int> s{3, 1, 4, 1, 5, 9, 2, 6};  // duplicates removed, sorted
    for (int v : s) std::cout << v << " ";  // 1 2 3 4 5 6 9
    std::cout << "
";

    s.insert(7);
    auto [it, inserted] = s.insert(4);    // C++17 structured bindings
    std::cout << "4 inserted? " << inserted << "
";  // false (already in set)

    std::cout << "count(9)=" << s.count(9) << "
";   // 1
    std::cout << "count(8)=" << s.count(8) << "
";   // 0

    // ── map ───────────────────────────────────────────────────
    std::map<std::string, int> word_count;
    std::string words[] = {"apple", "banana", "apple", "cherry", "banana", "apple"};
    for (const auto& w : words) word_count[w]++;  // default-init to 0

    for (const auto& [word, count] : word_count) {  // sorted by key
        std::cout << word << ": " << count << "
";
    }

    // Safe lookup - don't use [] (inserts default if missing)
    if (auto it = word_count.find("orange"); it != word_count.end()) {
        std::cout << "orange: " << it->second << "
";
    } else {
        std::cout << "orange not found
";
    }

    // map[] inserts zero if key missing - dangerous for read-only checks
    // word_count["newkey"];  ← inserts "newkey":0 into the map!

    // ── unordered_map - O(1) average ──────────────────────────
    std::unordered_map<std::string, double> prices;
    prices["apple"]   = 0.99;
    prices["banana"]  = 0.49;
    prices.emplace("cherry", 1.29);
    prices.try_emplace("apple", 9.99);   // doesn't overwrite existing key

    std::cout << "apple price: " << prices["apple"] << "
";    // 0.99
    std::cout << "bucket count: " << prices.bucket_count() << "
";
    std::cout << "load factor: " << prices.load_factor() << "
";

    prices.reserve(100);  // pre-allocate hash buckets - avoids rehashing

    // ── Custom key unordered_map ──────────────────────────────
    std::unordered_map<Person, std::string,
                       PersonHash, PersonEqual> phone_book;
    phone_book[{"Alice", 30}] = "+1-555-0100";
    phone_book[{"Bob",   25}] = "+1-555-0101";
    std::cout << phone_book[{"Alice", 30}] << "
";

    // ── multimap - allows duplicate keys ──────────────────────
    std::multimap<std::string, int> multi;
    multi.emplace("a", 1);
    multi.emplace("a", 2);  // Two entries with key "a"
    auto range = multi.equal_range("a");
    for (auto i = range.first; i != range.second; ++i)
        std::cout << i->first << ":" << i->second << " ";  // a:1 a:2
    std::cout << "
";

    return 0;
}

Common Mistakes

  • `map[key]` inserts a default value if the key doesn't exist - `if (m["missing"] > 0)` silently inserts `{"missing": 0}` into the map. Always use `find()` or `count()` for read-only lookups.
  • Bad hash function causes O(n) unordered_map - if all keys hash to the same bucket, every operation degrades to O(n). XOR-combining hashes as shown (`h1 ^ (h2 << 1)`) is minimal; for production, use `boost::hash_combine` or FNV-1a.
  • `std::map` vs `std::unordered_map` as default - many programmers default to `map` out of habit. For most use cases without ordering requirements, `unordered_map` is 10-100x faster. Know when to switch.

Tip

Tip

Practice Associative Containers set map unorderedmap in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Red-Black Tree vs Hash Table complexity and container decision trade-offs

Practice Task

Note

Practice Task - (1) Write a working example of Associative Containers set map unorderedmap from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Associative Containers set map unorderedmap is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • `std::set` and `std::map` are **ordered** containers backed by a red-black tree - O(log n) lookup, insert, and erase, with elements always sorted.
  • `map[key]` inserts a default value if the key doesn't exist - `if (m["missing"] > 0)` silently inserts `{"missing": 0}` into the map. Always use `find()` or `count()` for read-only lookups.
  • Bad hash function causes O(n) unordered_map - if all keys hash to the same bucket, every operation degrades to O(n). XOR-combining hashes as shown (`h1 ^ (h2 << 1)`) is minimal; for production, use `boost::hash_combine` or FNV-1a.
  • `std::map` vs `std::unordered_map` as default - many programmers default to `map` out of habit. For most use cases without ordering requirements, `unordered_map` is 10-100x faster. Know when to switch.

Topics in This Module

0/7 done