C++ set
π C++ set (STL)
std::set is an associative container in the C++ STL that stores unique elements in a sorted order (by default, ascending).
It is typically implemented using a balanced binary search tree (RedβBlack Tree).
πΉ 1. Why Use set?
Automatically keeps elements sorted
Stores unique values only
Fast search, insert, delete β O(log n)
Useful when duplicates are not allowed
πΉ 2. Include Header
πΉ 3. Declaring a Set
With initialization:
Result:
πΉ 4. Inserting Elements
Duplicate insert ignored:
πΉ 5. Accessing Elements
β No indexing ([] not allowed)
β Access using iterators:
πΉ 6. Finding Elements
πΉ 7. Erasing Elements
πΉ 8. Size & Empty
πΉ 9. Lower Bound & Upper Bound
πΉ 10. Custom Sorting (Descending Order)
πΉ 11. set vs multiset
| Feature | set | multiset |
|---|---|---|
| Duplicates | β No | β Yes |
| Sorted | β Yes | β Yes |
| Insert | O(log n) | O(log n) |
πΉ 12. set vs unordered_set
| Feature | set | unordered_set |
|---|---|---|
| Order | Sorted | No order |
| Search | O(log n) | O(1) average |
| Implementation | Tree | Hash table |
πΉ 13. Example: Remove Duplicates
πΉ 14. Time Complexity
| Operation | Complexity |
|---|---|
| Insert | O(log n) |
| Find | O(log n) |
| Erase | O(log n) |
β Common Mistakes
π Summary
setstores unique sorted elementsNo indexing allowed
Balanced BST based
Fast search and insert
Ideal when uniqueness + order matters
