A Set is a container which stores unique elements in some sorted order. It is an implementation of a Self-Balancing Binary Search Tree, specifically a Red-Black Tree which ensures,
- Search, insert, and delete in O(log n) time.
- Does not allow duplicates.
- Elements are always sorted in ascending order by default. You can also choose your own way of ordering them using a custom rule (comparator).
- Compared to unordered_set, the time taken to search, insert, and delete an higher, but we get elements in sorted order and also support additional functions like upper_bound() and lower_bound().
Let us take a look at an example to create a set and traverse it.
Syntax
The set container is defined as std::set class template inside <set> header file.
set<T> s;
where,
- T: Data type of elements in the set.
- s: Name assigned to the set.
Basic Operations
Basic operations on set containers are shown below:
1. Inserting Elements
- The insert() operation adds a new element to the set only if it not already present.
- If the element already exists, insert() does nothing (since duplicates are not allowed in set).
2. Searching Elements
- The find() function is used to check whether an element exists. It returns an iterator to the element if found, else returns end() if the element is not found.
- The count() function can also be used to check existence, returns 1 if the element is present, 0 otherwise.
OutputElement found: 1
2 exists in the set
All elements: 1 2 3
3. Traversing
- Loops (like range-based for loop or iterators) can be used to traverse all elements in a set.
- The traversal visits elements in sorted order (by default ascending, or according to a custom comparator).
4. Deleting Elements
To delete an element from a set, use erase(), it removes the element if it exists, else does nothing.