Přeskočit na obsah

Associative Containers: map, set, unordered_map

Learn about ordered and unordered associative containers — maps, sets, and their multi- and unordered variants. Understand when to choose trees vs hash tables.

Ordered vs Unordered Associative Containers

The STL provides two families of associative containers:

Ordered (implemented as red-black trees):
-std::map— sorted key-value pairs, unique keys
-std::set— sorted unique keys
-std::multimap— sorted key-value pairs, duplicate keys allowed
-std::multiset— sorted keys, duplicates allowed

Unordered (implemented as hash tables):
-std::unordered_map— hash-based key-value, unique keys
-std::unordered_set— hash-based unique keys
-std::unordered_multimap— hash-based, duplicate keys
-std::unordered_multiset— hash-based, duplicates

Ordered containers keep elements sorted and provide O(log n) lookup, insertion, and deletion. Unordered containers use hashing for O(1) average-case operations but O(n) worst-case if many collisions occur.

Using map and set

std::mapstores key-value pairs sorted by key.std::setstores unique sorted values. Both are implemented as self-balancing red-black trees, guaranteeing O(log n) operations.

map_set.cpp
#include <map>
#include <set>
#include <string>
#include <iostream>

int main() {
    // std::map — sorted key-value pairs
    std::map<std::string, int> ages;
    ages["Alice"] = 30;              // insert or update
    ages["Bob"]   = 25;
    ages.insert({"Charlie", 35});    // insert only if key absent
    ages.emplace("Diana", 28);       // construct in-place

    // Lookup
    if (auto it = ages.find("Bob"); it != ages.end()) {
        std::cout << it->first << " is " << it->second << '\n';
    }

    // C++17 structured bindings — elegant map iteration
    for (const auto& [name, age] : ages) {
        std::cout << name << ": " << age << '\n';
    }
    // Output is sorted by key: Alice, Bob, Charlie, Diana

    // std::set — sorted unique values
    std::set<int> primes = {2, 3, 5, 7, 11, 13};
    primes.insert(5);                // no effect — 5 already present
    primes.insert(17);               // inserted

    if (primes.contains(7)) {        // C++20
        std::cout << "7 is prime\n";
    }

    // count() — returns 0 or 1 for set (useful pre-C++20)
    if (primes.count(4) == 0) {
        std::cout << "4 is not prime\n";
    }

    // lower_bound / upper_bound — range queries
    auto lo = primes.lower_bound(5);
    auto hi = primes.upper_bound(11);
    for (auto it = lo; it != hi; ++it) {
        std::cout << *it << ' ';     // 5 7 11
    }
    std::cout << '\n';
}

Unordered Containers and Custom Hash Functions

Unordered containers use hash tables for O(1) average-case lookup. For custom key types, you must provide a hash function and an equality operator.

unordered_custom.cpp
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <iostream>

// Custom type as key
struct Point {
    int x, y;
    bool operator==(const Point&) const = default;  // C++20
};

// Custom hash function
struct PointHash {
    std::size_t operator()(const Point& p) const {
        // Combine hashes — a common pattern
        auto h1 = std::hash<int>{}(p.x);
        auto h2 = std::hash<int>{}(p.y);
        return h1 ^ (h2 << 1);  // simple combine (consider better hashes in production)
    }
};

int main() {
    // Basic unordered_map — O(1) average lookup
    std::unordered_map<std::string, double> prices;
    prices["apple"]  = 1.50;
    prices["banana"] = 0.75;
    prices["cherry"] = 3.00;

    // try_emplace (C++17) — only constructs value if key is absent
    prices.try_emplace("apple", 9.99);   // no-op, "apple" exists
    prices.try_emplace("date", 4.50);    // inserted

    // extract and insert (C++17 node API)
    auto node = prices.extract("banana");
    if (!node.empty()) {
        node.key() = "plantain";          // rename key without copy
        prices.insert(std::move(node));
    }

    for (const auto& [fruit, price] : prices) {
        std::cout << fruit << ": $" << price << '\n';
    }

    // Custom type as key
    std::unordered_set<Point, PointHash> points;
    points.insert({1, 2});
    points.insert({3, 4});
    points.insert({1, 2});   // duplicate — not inserted
    std::cout << "Unique points: " << points.size() << '\n';  // 2
}

Multimap and Multiset

std::multimapandstd::multisetallow duplicate keys. Useequal_range()to find all entries with a given key.

multimap_multiset.cpp
#include <map>
#include <set>
#include <iostream>
#include <string>

int main() {
    // multimap — multiple values per key
    std::multimap<std::string, std::string> phone_book;
    phone_book.insert({"Alice", "555-0100"});
    phone_book.insert({"Alice", "555-0101"});  // duplicate key OK
    phone_book.insert({"Bob",   "555-0200"});

    // equal_range returns a pair of iterators [first, last)
    auto [begin, end] = phone_book.equal_range("Alice");
    std::cout << "Alice's numbers:\n";
    for (auto it = begin; it != end; ++it) {
        std::cout << "  " << it->second << '\n';
    }

    // multiset — count duplicates
    std::multiset<int> ms = {1, 2, 2, 3, 3, 3};
    std::cout << "Count of 3: " << ms.count(3) << '\n';  // 3
}

Custom Comparators for Ordered Containers

Ordered containers default tostd::less(ascending order). You can supply a custom comparator as the third template argument:

std::set<int, std::greater<int>> descending = {1, 5, 3};
// iteration order: 5, 3, 1

For custom types, you can either define operator< in your class or pass a comparator functor or lambda:

auto cmp = [](const Point& a, const Point& b) {
 return a.x < b.x || (a.x == b.x && a.y < b.y);
};
std::set<Point, decltype(cmp)> point_set(cmp);

In C++20, you can use the spaceship operator (operator<=>) to automatically generate all comparison operators.

Úskalí

Usingoperator[]on astd::maporstd::unordered_mapinserts a default-constructed value if the key does not exist. This is a common source of subtle bugs:

std::map<std::string, int> m;
int val = m["missing"]; // inserts {"missing", 0} into the map!

Use find(), count(), or contains() (C++20) for lookup without modification. Use at() if you want an exception on missing keys.

Osvědčený postup

Použijteunordered_map/unordered_set, když potřebujete pouze vyhledávání, vkládání a mazání – průměrný případ O(1) převyšuje O(log n) pro velké sbírky.

Použijtemap/set, když potřebujete:
- Seřazené pořadí iterací
- Rozsahové dotazy (lower_bound,upper_bound,equal_range)
- Garantovaný nejhorší případ O(log n) (žádné patologické kolize hash)

U malých sbírek (méně než ~100 prvků) může seřazenýstd::vectorsstd::lower_boundpřekonat oba kvůli lokalitě mezipaměti.

Klíčové poznatky
  • std::mapastd::setpoužívají červeno-černé stromy — operace O(log n) se seřazeným pořadím
  • std::unordered_mapastd::unordered_setpoužívají hašovací tabulky – průměr O(1), ale vyžadují hašovací funkci
  • Pro čistou iteraci mapy použijte strukturované vazby C++17 (auto& [key, val]).
  • operator[]na mapách tiše vkládá výchozí hodnoty — pro bezpečné vyhledávání použijtefind()nebocontains()
  • Vlastní typy jako klíče vyžadujíoperator<(objednané) nebo hashovací funkci +operator==(neuspořádané)
  • try_emplace(C++17) se vyhýbá konstrukci hodnoty, pokud klíč již existuje

Kvíz — Otestujte své znalosti

(15 XP)

1. Jaká je průměrná časová složitost vyhledávání v`std::unordered_map`?

2. Co se stane, když použijete`operator[]`s klíčem, který v`std::map`neexistuje?

3. Který kontejner byste si měli vybrat, pokud potřebujete seřazené dotazy na iteraci A rozsah (lower_bound/upper_bound)?