01 / 20

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.

C++

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).

std::set
Elements stored in sorted order. Backed by a balanced binary search tree (red-black tree).
std::unordered_set
Elements in no particular order. Backed by a hash table with buckets.

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.

std::vector (linear scan)
Checking membership requires scanning every element: \( O(n) \).
std::set
Binary search tree lookup: \( O(\log n) \) time per query.
unordered_set
Hash table lookup: \( O(1) \) average time per query.

Tree vs Hash Table

std::set (BST) 20 10 30 5 15 25 35 Sorted: 5, 10, 15, 20, 25, 30, 35
Lookup: \( O(\log n) \)
unordered_set (Hash) [0] 20 [1] 15 35 [2] 10 [3] 5 25 30 No guaranteed order
Lookup: \( O(1) \) average

The Core API

Both std::set and std::unordered_set share the same essential interface for membership testing:

1
insert(value): add an element. Ignored if already present.
2
count(value): returns 1 if found, 0 if not. Perfect for membership checks.
3
find(value): returns an iterator to the element, or end() if absent.
4
erase(value): remove an element by value.
5
size(): number of unique elements currently stored.

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

Choose std::set
You need elements in sorted order, or you want to iterate from smallest to largest. Also useful when you need range queries (lower_bound, upper_bound).
Choose unordered_set
You only care about "is it in here?" and want the fastest possible lookup. Order doesn't matter. Great for large datasets.

Headers & Setup

#include <set> // for std::set #include <unordered_set> // for std::unordered_set #include <iostream> int main() { std::set<int> ordered = {3, 1, 4, 1, 5}; std::unordered_set<int> fast = {3, 1, 4, 1, 5}; // Both store: {1, 3, 4, 5} (duplicate 1 dropped) // ordered iterates: 1 3 4 5 (sorted) // fast iterates in arbitrary order }

Step-by-Step: Membership Test

1
Include the header: <set> or <unordered_set>.
2
Declare your set with the element type: std::set<int> or std::unordered_set<string>.
3
Populate with insert() or brace initialization.
4
Query membership with count(value) (returns 0 or 1) or find(value) != s.end().
5
Act on the result: branch with an if statement based on the lookup.

Example 1: Finding Duplicates

Given a vector of IDs, check if any ID appears more than once.

#include <unordered_set> #include <vector> #include <iostream> bool hasDuplicate(const std::vector<int>& ids) { std::unordered_set<int> seen; for (int id : ids) { if (seen.count(id)) // already in set? return true; seen.insert(id); } return false; }

Example 2: Allowed Words Filter

Filter user input against an allowed list of words.

#include <set> #include <string> #include <iostream> int main() { std::set<std::string> allowed = { "apple", "banana", "cherry" }; std::string input = "banana"; if (allowed.count(input)) { std::cout << input << " is allowed!\n"; } else { std::cout << input << " is NOT allowed.\n"; } }

Example 3: Unique Characters

Count how many distinct characters appear in a string.

#include <unordered_set> #include <string> #include <iostream> int main() { std::string word = "mississippi"; std::unordered_set<char> chars( word.begin(), word.end() ); std::cout << "Unique chars: " << chars.size() << "\n"; // Output: Unique chars: 4 (m, i, s, p) }

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()

std::set<int> s; s.insert(10); // s = {10} s.insert(20); // s = {10, 20} s.insert(10); // duplicate ignored, s = {10, 20} // insert() returns a std::pair<iterator, bool> auto [it, ok] = s.insert(30); if (ok) std::cout << "Inserted " << *it << "\n";

Common Mistakes

✕ Using [] to Access
Sets do not support operator[]. That is for maps. Use count() or find() instead.
✕ Forgetting the Header
Including <set> does not give you unordered_set. You need <unordered_set> separately.
✕ Modifying Elements
Set elements are const. You cannot change an element in-place; you must erase and re-insert.

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?