C++ Sets β Store Sorted Unique Elements with std::set
Introduction β Why Use std::set in C++
In C++ applications where duplicates are not allowed and fast search, insertion, and deletion are required, std::set is the ideal choice. It stores elements in a sorted order and provides logarithmic time complexity for all operations, thanks to its balanced tree structure.
In this guide, youβll learn:
- What
std::setis and how it works - Key operations like
insert(),find(),erase() - How to use iterators and custom sort orders
- Best practices and real-world use cases
What Is a C++ Set?
A std::set is an ordered associative container that contains only unique keys. It stores the keys in ascending order by default using a Red-Black Tree (balanced BST).
Include the header:
#include <set>
Declare a set:
set<int> s;
Code Examples β With Output
Insert and Traverse
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert(30);
s.insert(10);
s.insert(20);
s.insert(10); // Duplicate ignored
for (int x : s) cout << x << " ";
return 0;
}
Output:
10 20 30
Search and Erase
if (s.find(20) != s.end())
s.erase(20);
Set Member Functions
| Function | Description |
|---|---|
insert(val) | Adds a new element (if not present) |
erase(val) | Removes element |
find(val) | Returns iterator to element if found |
count(val) | Returns 1 if element exists, else 0 |
size() | Returns number of elements |
clear() | Removes all elements |
begin()/end() | Start/end iterators for traversal |
Custom Sort Order with Comparator
struct Desc {
bool operator()(int a, int b) const {
return a > b; // Descending
}
};
set<int, Desc> descSet;
Iterating a Set
for (set<int>::iterator it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
Set vs Multiset vs Unordered Set
| Feature | set | multiset | unordered_set |
|---|---|---|---|
| Duplicates allowed? | No | Yes | No |
| Order | Sorted | Sorted | Unordered |
| Lookup complexity | O(log n) | O(log n) | O(1) average |
| Underlying structure | Balanced tree | Balanced tree | Hash table |
Best Practices & Tips
Use count() if you only need to check for existence
For heavy insert/delete workloads, consider unordered_set
Avoid modifying set elements via iteratorsβsets reorder elements automatically
Use a custom comparator for descending order or complex types
Use Cases for Sets
Unique Element Tracking β Email lists, usernames, identifiers
Sorted Data Retrieval β Maintain live sorted datasets
Efficient Searching β Membership tests and quick lookups
Event Logs β Avoid duplicate event IDs
Mathematical Sets β Implement union, intersection, difference
Summary β Recap & Next Steps
Key Takeaways:
std::setstores unique, automatically sorted elements- Efficient for searching, insertion, and deletion (O(log n))
- Supports iterators and custom comparators
Real-World Relevance:
C++ sets are used in simulations, indexes, validation systems, constraint checkers, and anywhere uniqueness and order are critical.
Next Steps:
Learn about C++ Maps to associate keys with values in sorted order.
FAQ β C++ Sets
Are duplicates allowed in std::set?
No. Use multiset if duplicates are needed.
Can I change an element in a set directly?
No. You must remove and re-insert to modify value.
How is set sorted?
By default in ascending order using < operator.
Can I sort a set in descending order?
Yes. Use a custom comparator.
Is find() faster than looping through the set?
Yes. find() uses binary search (O(log n)).
Share Now :
