Lesson 31 of 45
C++Lesson 31: Set and Unordered Set
11 min
Course progress69%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 31 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
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.
insert, find, erase, count.std::set provides ordered iteration; unordered_set does not guarantee order.std::set) or hashers/equality predicates (std::unordered_set).std::set for automatic sorting and duplicate eliminationstd::set<int> s;
s.insert(5);
s.insert(3);
s.insert(5); // duplicate ignored
for (int v : s) std::cout << v << ' '; // prints 3 5
std::cout << '\
';
std::unordered_set with a custom hash for a user‑defined typestruct Point { int x, y; };
struct PointHash {
std::size_t operator()(const Point& p) const noexcept {
return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
}
};
struct PointEq {
bool operator()(const Point& a, const Point& b) const noexcept {
return a.x == b.x && a.y == b.y;
}
};
std::unordered_set<Point, PointHash, PointEq> pts;
pts.insert({1,2});
pts.insert({1,2}); // duplicate ignored by hash/equality
std::cout << \"Set size: \" << pts.size() << '\
';
Tip: Reserve bucket count with
pts.reserve(n)when you know the expected number of elements to reduce rehashing.
<Alert type="info">When ordering matters (e.g., for range queries), prefer std::set. For fast membership tests, choose std::unordered_set.