๐ 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 :
