Unordered Containers
Hash-based set and map
Interview Relevant: O(1) average lookup
Unordered Containers
Hash table based. O(1) average operations.
Code Examples
Hash-based containers for fast lookup.
cpp
1#include <unordered_map>
2#include <unordered_set>
3
4// unordered_set
5unordered_set<int> uset = {3, 1, 4};
6uset.insert(2);
7uset.erase(1);
8bool found = uset.count(3);
9
10// unordered_map
11unordered_map<string, int> umap;
12umap["key"] = 42;
13
14// Hash table info
15umap.bucket_count(); // Number of buckets
16umap.load_factor(); // Elements per bucket
17umap.max_load_factor(0.75); // Set threshold
18
19// Custom hash for user types
20struct Point { int x, y; };
21struct PointHash {
22 size_t operator()(const Point& p) const {
23 return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1);
24 }
25};
26struct PointEqual {
27 bool operator()(const Point& a, const Point& b) const {
28 return a.x == b.x && a.y == b.y;
29 }
30};
31unordered_set<Point, PointHash, PointEqual> points;
32
33// When to use:
34// - Need O(1) lookup: unordered
35// - Need ordered iteration: ordered
36// - Need range queries: ordered