Skip to content

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.

Beginner 12 min read·Lesson 36 of 40 in C++ Programming

Learning objectives

  • Insert and test membership in sets
  • Use lower_bound/upper_bound for range queries
  • Compute union, intersection and difference

Definition

std::set stores unique keys in sorted order with O(log n) operations; std::unordered_set stores unique keys in a hash table with average O(1) operations; std::multiset allows 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

C++
std::set<int> s{5, 1, 3};
auto [it, ok] = s.insert(3); // ok == false
bool has = s.count(5);
auto ge4 = s.lower_bound(4); // points to 5
std::set<int> out;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(out, out.begin()));
  • 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

C++
#include <iostream>
#include <set>
#include <vector>
int main() {
std::vector<int> rolls{102, 101, 105, 101, 102, 103};
std::set<int> unique(rolls.begin(), rolls.end());
for (int r : unique) std::cout << r << ' ';
std::cout << "(" << unique.size() << " unique)\n";
auto [it, inserted] = unique.insert(105);
std::cout << "105 inserted again? " << inserted << '\n';
return 0;
}
Output
101 102 103 105 (4 unique)
105 inserted again? 0

Range queries

C++
#include <iostream>
#include <set>
int main() {
std::set<int> slots{9, 11, 14, 16};
int want = 12;
auto it = slots.lower_bound(want);
std::cout << "next free slot at or after " << want << ": " << (it != slots.end() ? *it : -1) << '\n';
std::cout << "slots before 14: " << std::distance(slots.begin(), slots.lower_bound(14)) << '\n';
return 0;
}
Output
next free slot at or after 12: 14
slots before 14: 2

More examples

Set algebra on course enrolments

C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
void print(const char* label, const std::set<std::string>& s) {
std::cout << label << ':';
for (const auto& x : s) std::cout << ' ' << x;
std::cout << '\n';
}
int main() {
std::set<std::string> cpp{"Asha", "Ravi", "Meera", "Kiran"};
std::set<std::string> java{"Ravi", "Neha", "Kiran"};
std::set<std::string> both, either, only_cpp;
std::set_intersection(cpp.begin(), cpp.end(), java.begin(), java.end(), std::inserter(both, both.begin()));
std::set_union(cpp.begin(), cpp.end(), java.begin(), java.end(), std::inserter(either, either.begin()));
std::set_difference(cpp.begin(), cpp.end(), java.begin(), java.end(), std::inserter(only_cpp, only_cpp.begin()));
print("both", both);
print("either", either);
print("only C++", only_cpp);
return 0;
}
Output
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::inserter adds 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:

TextOutput
both: Kiran Ravi
either: Asha Kiran Meera Neha Ravi
only C++: Asha Meera

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

auto it = s.find(3);
*it = 4;

Prefer

s.erase(3);
s.insert(4);

Set elements are const because changing them would break the ordering.

Using set algorithms on unsorted vectors

Avoid

std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), out); // unsorted

Prefer

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_intersection(...);

Set algorithms require sorted input ranges.

Important notes

  • std::set member lower_bound is O(log n); the generic std::lower_bound on a set is O(n) because set iterators aren't random access.
  • C++20 adds contains for 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

  1. 1
    Read words and print those that appear in both of two sentences.
  2. 2
    Use 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?
Practise this topic