Set
Lesson 8 of 23 in Coddy's C++ - Standard Template Library course.
In this chapter you'll learn about Associative Containers and how they work. We are beginning with the set data structure.
The C++ Set is a type of associative container which stores unique elements of the same type in a sorted order. This means that each element can appear only once in a set.
Sets are frequently used in competitive programming whenever there is a need to store unique elements sorted without spending more time and complexity using other data structures, like the array, sorting algorithms and removing repeating elements.
set<int> mySet = {5, 10, 3, 5};We implement sets using the #include <set> header file or we can include all of the header files as mentioned in previous lessons with the #include <bits/stdc++.h>
set<int> mySet = {5, 10, 3, 5};
for (int i = mySet.begin(); i != mySet.end(); i++)
cout << *i << " ";Output:
3 5 10As you can see from above we declared a set with initial values. We used an iterator pointing to the first element, looped through the set and printed all of the elements. We can see that the set itself, removed the repeating elements and also sorted them beginning with the smallest one.
We insert elements in the set using the insert() method.
mySet.insert(50);Also, values of elements cannot be modified once they're added to the set, it is only possible to remove them and add new elements.
Set Methods
| Method | Functionality |
| begin() | Returns an iterator pointing to the first element of the set |
| end() | Returns an iterator pointing to the last element of the set |
| size() | Returns the number of elements in the set |
| empty() | Return whether the set is empty (1) or not (0) |
| count() | Returns 1 if an element is present in the set, and 0 otherwise |
Challenge
EasyGiven 10 numbers from input. Using a set, output the unique numbers only.
Input
5
10
1
5
3
5
10
8
6
7Output
5
10
1
3
8
6
7Try it yourself
#include <set>
#include <iostream>
using namespace std;
int main()
{
// Enter your code here
return 0;
}