std::set &
unordered_set
Master C++ associative containers for fast membership testing: when to use ordered vs. hash-based sets, and how to write clean, efficient code.
What Is a Set?
A set is a collection of unique elements with no duplicates. In C++, the Standard Library gives you two flavors: std::set (ordered, tree-based) and std::unordered_set (hash-based).
Why Membership Testing Matters
The most common question you ask a set is: "Is this element present?" This is called a membership test. Choosing the right container determines whether that check is fast or slow.
Tree vs Hash Table
The Core API
Both std::set and std::unordered_set share the same essential interface for membership testing:
Complexity at a Glance
| Operation | std::set | unordered_set |
|---|---|---|
| insert | \( O(\log n) \) | \( O(1) \) avg |
| find / count | \( O(\log n) \) | \( O(1) \) avg |
| erase | \( O(\log n) \) | \( O(1) \) avg |
| Iteration order | Sorted | Arbitrary |
| Worst case lookup | \( O(\log n) \) | \( O(n) \) |
set vs unordered_set: When to Choose
Headers & Setup
Step-by-Step: Membership Test
Example 1: Finding Duplicates
Given a vector of IDs, check if any ID appears more than once.
Example 2: Allowed Words Filter
Filter user input against an allowed list of words.
Example 3: Unique Characters
Count how many distinct characters appear in a string.
find() vs count()
Both test membership, but they return different things:
| Method | Returns | Best For |
|---|---|---|
| count(val) | 0 or 1 (an integer) | Simple yes/no check |
| find(val) | Iterator (or end()) | When you need to use the element after finding it |
| contains(val) | bool (C++20) | Cleanest syntax if C++20 available |
Inserting with insert()
Common Mistakes
Question 1 of 5
What is the average-case time complexity of count() on an std::unordered_set with \( n \) elements?
Question 2 of 5
What does s.count(42) return if 42 is not in the set?
Question 3 of 5
After this code runs, what is s.size()?std::set<int> s = {5, 3, 5, 1, 3};
Question 4 of 5
Which header must you include to use std::unordered_set?
Question 5 of 5
When should you prefer std::set over std::unordered_set?