Lesson 25 of 45 · C++
Lesson 31: Set and Unordered Set
Duration: 11 min
Lesson 25 of 45 · C++
Duration: 11 min
std::set stores unique elements in a sorted order using a balanced binary tree (typically a red‑black tree). std::unordered_set uses a hash table for average O(1) lookup, insertion, and deletion.\n\n---\n\n## Typical operations\n- insert, find, erase, count.\n- std::set provides ordered iteration; unordered_set does not guarantee order.\n- Custom comparators (std::set) or hashers/equality predicates (std::unordered_set).\n\n---\n\n## Example: Using std::set for automatic sorting and duplicate elimination\ncpp\nstd::set<int> s;\ns.insert(5);\ns.insert(3);\ns.insert(5); // duplicate ignored\nfor (int v : s) std::cout << v << ' '; // prints 3 5\nstd::cout << '\\n';\n\n\n## Example: std::unordered_set with a custom hash for a user‑defined type\ncpp\nstruct Point { int x, y; };\nstruct PointHash {\n std::size_t operator()(const Point& p) const noexcept {\n return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);\n }\n};\nstruct PointEq {\n bool operator()(const Point& a, const Point& b) const noexcept {\n return a.x == b.x && a.y == b.y;\n }\n};\nstd::unordered_set<Point, PointHash, PointEq> pts;\npts.insert({1,2});\npts.insert({1,2}); // duplicate ignored by hash/equality\nstd::cout << \"Set size: \" << pts.size() << '\\n';\n\n\n> Tip: Reserve bucket count with pts.reserve(n) when you know the expected number of elements to reduce rehashing.\n\n---\n\n<Alert type="info">When ordering matters (e.g., for range queries), prefer std::set. For fast membership tests, choose std::unordered_set.