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::map stores key-value pairs sorted by key. std::set stores unique sorted values. Both are implemented as self-balancing red-black trees, guaranteeing O(log n) operations.
#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.
#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::multimap and std::multiset allow duplicate keys. Use equal_range() to find all entries with a given key.
#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 to std::less (ascending order). You can supply a custom comparator as the third template argument:
``cpp``
std::set
// iteration order: 5, 3, 1
For custom types, you can either define operator< in your class or pass a comparator functor or lambda:
``cpp``
auto cmp = [](const Point& a, const Point& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
};
std::set
In C++20, you can use the spaceship operator (operator<=>) to automatically generate all comparison operators.
Using operator[] on a std::map or std::unordered_map inserts a default-constructed value if the key does not exist. This is a common source of subtle bugs:
``cpp``
std::map
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.
Use unordered_map/unordered_set when you only need lookup, insertion, and deletion — the O(1) average case beats O(log n) for large collections.
Use map/set when you need:
- Sorted iteration order
- Range queries (lower_bound, upper_bound, equal_range)
- Guaranteed O(log n) worst-case (no pathological hash collisions)
For small collections (fewer than ~100 elements), a sorted std::vector with std::lower_bound can outperform both due to cache locality.
std::mapandstd::setuse red-black trees — O(log n) operations with sorted orderstd::unordered_mapandstd::unordered_setuse hash tables — O(1) average but require a hash function- Use C++17 structured bindings (
auto& [key, val]) for clean map iteration operator[]on maps silently inserts default values — usefind()orcontains()for safe lookup- Custom types as keys require
operator<(ordered) or a hash function +operator==(unordered) try_emplace(C++17) avoids constructing the value if the key already exists
Quiz — Test Your Knowledge
(15 XP)1. What is the average time complexity of lookup in `std::unordered_map`?
2. What happens when you use `operator[]` with a key that doesn't exist in a `std::map`?
3. Which container should you choose if you need sorted iteration AND range queries (lower_bound/upper_bound)?