← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 11 of 15

C++ set and multiset

What is a set?

std::set stores unique elements in sorted order, implemented as a balanced binary search tree. It is useful when you need a collection with no duplicates and fast ordered lookups, in O(log n) time.

Example: What is a set?

cpp
#include <iostream>
#include <set>

int main() {
	std::set<int> nums = {3, 1, 2};
	for (int n : nums) std::cout << n << " ";
	std::cout << std::endl;
	return 0;
}

Inserting and Erasing

insert() adds an element and returns a pair indicating whether it was newly inserted. erase() removes an element by value or by iterator. Because a set enforces uniqueness automatically, inserting a duplicate value simply does nothing and leaves the set unchanged.

Example: Inserting and Erasing

cpp
#include <iostream>
#include <set>

int main() {
	std::set<int> nums;
	nums.insert(5);
	nums.insert(5);
	nums.erase(5);
	std::cout << nums.size() << std::endl;
	return 0;
}

set vs multiset

std::set silently ignores duplicate inserts. std::multiset allows multiple equal elements, all stored in sorted order, useful for keeping a sorted collection with repeats (e.g. sorted scores).

Example: set vs multiset

cpp
#include <iostream>
#include <set>

int main() {
	std::set<int> s;
	s.insert(5);
	s.insert(5);
	std::multiset<int> ms;
	ms.insert(5);
	ms.insert(5);
	std::cout << s.size() << " " << ms.size() << std::endl;
	return 0;
}

Iterating over a set

Iterating a set visits elements in ascending sorted order automatically, without needing an explicit sort step. This ordering guarantee is what distinguishes std::set from std::unordered_set, which offers no such guarantee.

Example: Iterating over a set

cpp
#include <iostream>
#include <set>

int main() {
	std::set<int> nums = {5, 1, 3};
	for (int n : nums) std::cout << n << " ";
	std::cout << std::endl;
	return 0;
}

Searching a set

find() returns an iterator to the element or end() if missing. count() returns 0 or 1 for a set (or the number of matches for a multiset). Both run in O(log n). Since count() can only ever return 0 or 1 for a plain set, many developers prefer find() for clearer, non-boolean-looking intent.

Example: Searching a set

cpp
#include <iostream>
#include <set>

int main() {
	std::set<int> nums = {1, 2, 3};
	auto it = nums.find(2);
	std::cout << (it != nums.end()) << " " << nums.count(2) << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.