Sets
A set is container in C++ which stores values of the same type in a way that:
- Each value appears only once.
- The values are kept sorted (by default, smallest to largest).
- You can quickly check if something exists in it.
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> numbers = {5, 2, 9, 2, 1};
for (int x : numbers)
cout << x << " ";
}Output:
1 2 5 9
Notice that the second 2 disappeared — because a set doesn’t allow duplicates.
Creating a set
To use a set, include the header:
#include <set>Then you can create a set like this:
set<int> mySet; // empty set of integers
set<string> names; // set of strings
set<char> letters = {'a','b','c'};
Note
You can also initialize it with values using braces { }.
Basic operations
| Operation | Example | Explanation |
|---|---|---|
insert(x) |
s.insert(5); |
Adds 5 to the set. (If 5 already exists, nothing happens.) |
erase(x) |
s.erase(5); |
Removes 5 if it’s there. |
find(x) |
if (s.find(5) != s.end()) |
Checks if 5 exists. Returns an iterator (like a pointer). |
count(x) |
if (s.count(5)) |
Returns 1 if found, 0 if not. Easier for beginners. |
size() |
s.size(); |
Number of elements. |
empty() |
s.empty(); |
Checks if the set has no elements. |
clear() |
s.clear(); |
Removes everything from the set. |
Example: Using a set
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert(3);
s.insert(1);
s.insert(4);
s.insert(3); // duplicate ignored
cout << "Elements: ";
for (int x : s) cout << x << " ";
cout << endl;
if (s.count(3))
cout << "3 is in the set" << endl;
s.erase(1);
cout << "After removing 1: ";
for (int x : s) cout << x << " ";
}Output:
Elements: 1 3 4
3 is in the set
After removing 1: 3 4
Iterating through a set
You can go through a set using a range-based for loop or an iterator.
for (int x : s)
cout << x << " ";Or:
for (auto it = s.begin(); it != s.end(); it++)
cout << *it << " ";Since sets are sorted, the elements will always appear in order.
Kinds of sets
| Type | Keeps order? | Allows duplicates? | Speed (roughly) | Notes |
|---|---|---|---|---|
set |
Yes | No | O(log n) | Balanced tree inside |
multiset |
Yes | Yes | O(log n) | Keeps multiple copies of the same value |
unordered_set |
No | No | O(1) average | Uses hashing, faster but order is random |
Tips: If you care about order — use set.
If you need to store duplicates — use multiset.
If you only care about speed — use unordered_set.
Example: removing duplicates
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1, 2, 2, 3, 4, 3, 1};
set<int> unique;
for (int x : nums)
unique.insert(x);
for (int x : unique)
cout << x << " ";
}Output:
1 2 3 4