C++ Using STL Unordered Set Program
In this tutorial, we will learn about the working of an Unordered Set and its implementation in the C++ programming language.
What is a Set?
In programming, a Set is used to store unique values of a list and also automatically providing an ordering to its elements. By default, the ordering is in ascending order.
The elements are inserted using the
insert() method. If the same value is inserted multiple times, the set automatically deletes the duplicates and only store the single copy of that element.
The elements of the Set are deleted using the
What is an Unordered Set?
An Unordered Set also stores only the single copy of the elements by removing the duplicates but does not sort the elements automatically as in Set.
An Unordered Set internally uses a Hash Table and hence the ordering is random depending upon the internally used Hash function.
For a better understanding of its implementation, refer to the well-commented C++ code given below.
using namespace std;
//Function to print the elements of the unordered set using an iterator
void show(unordered_set<int> s)
//declaring an iterator to iterate through the unordered set
for (i = s.begin(); i != s.end(); i++)
cout << *i << " "; //accessing the elements of the unordered set using * as i stores the address to each element
cout << endl;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate the working of Unordered Sets (Part 1), in CPP ===== \n\n\n\n";
cout << " *** Unordered Set automatically removes the duplicate elements and maintains a random ordering. *** \n\n";
cout << " *** This random ordering depends on the hash function that is used internally. *** \n\n";
//Unordered Set declaration (Unordered Set of integers)
//Filling the elements by using the insert() method.
cout << "\n\nFilling the Unordered Set with integers in random order."; //Unlike Set, this is not automatically sorted
cout << "\n\nThe elements of the Unordered Set are: ";
cout << "\n\nAfter deleting the element 39 from the unordered set using the erase() method, it becomes: ";
cout << "\n\n\n";
We hope that this post helped you develop a better understanding of the concept of Unordered Set and its implementation in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )