Module 8 · The Standard Template Library — topic 6 of 7
Sets (std::set and std::unordered_set)
Collections of unique values: sorted std::set, hashed std::unordered_set and std::multiset. Learn insertion results, membership tests, range queries and set operations.
Learning objectives
- Insert and test membership in sets
- Use lower_bound/upper_bound for range queries
- Compute union, intersection and difference
Definition
std::setstores unique keys in sorted order with O(log n) operations;std::unordered_setstores unique keys in a hash table with average O(1) operations;std::multisetallows duplicates.
Introduction
A set answers “have I seen this before?” and keeps each value once. std::set also keeps values sorted, so you can ask for the smallest element above a threshold in logarithmic time.
std::unordered_set trades that ordering for speed: membership tests take constant time on average using hashing. Choosing between them is the same decision as choosing between map and unordered_map.
Why it matters
Removing duplicates, checking membership and range queries are everyday tasks.
Set algebra (union/intersection) models real problems such as common friends or overlapping timetables.
Detailed explanation
auto [it, inserted] = s.insert(x); — inserted is false if x was already present.
Membership: s.count(x) (0 or 1) or s.contains(x) (C++20). Erase by value: s.erase(x).
lower_bound(x) returns the first element ≥ x; upper_bound(x) the first element > x.
Set algorithms in <algorithm> work on sorted ranges: set_union, set_intersection, set_difference, writing into an output iterator such as std::inserter.
multiset keeps duplicates; erase(x) removes all copies, erase(s.find(x)) removes one.
Syntax
- Elements are const; to change one, erase and reinsert.
- unordered_set has no lower_bound.
- Iteration order of set is ascending.
Code examples
Removing duplicates
101 102 103 105 (4 unique) 105 inserted again? 0
Range queries
next free slot at or after 12: 14 slots before 14: 2
More examples
Set algebra on course enrolments
both: Kiran Ravi either: Asha Kiran Meera Neha Ravi only C++: Asha Meera
Step-by-step explanation
- Both inputs are already sorted because they are std::sets.
std::inserteradds results into the output sets.- Intersection = in both; union = in either; difference = in the first only.
- Output sets are sorted alphabetically.
Expected output
Running “Set algebra on course enrolments” prints exactly:
Practical applications
- Social networks compute mutual friends with intersections.
- Spell checkers keep dictionaries in hash sets.
- Booking systems find the next free slot with lower_bound.
Best practices
- Use unordered_set for fast membership without order.
- Check the bool from insert to detect duplicates.
- Use lower_bound for nearest-value queries.
Common mistakes
Modifying an element through an iterator
Avoid
Prefer
Set elements are const because changing them would break the ordering.
Using set algorithms on unsorted vectors
Avoid
Prefer
Set algorithms require sorted input ranges.
Important notes
std::setmemberlower_boundis O(log n); the genericstd::lower_boundon a set is O(n) because set iterators aren't random access.- C++20 adds
containsfor sets and maps.
Key takeaways
- Sets keep unique values; std::set is sorted.
- insert returns whether insertion happened.
- Set algorithms need sorted ranges.
Try it yourself
- 1Read words and print those that appear in both of two sentences.
- 2Use a multiset to keep a running median of a stream of numbers.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?