C++ set and multiset
In this page:
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?
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: