In C++, unordered_set is an unordered associative container that stores unique elements.
- Internally uses a hashing to store elements which provides average constant time O(1) for insert, search and delete operations.
- Elements have no particular order and are best used when fast access is more important than sorted order. On other hand set is used for sorted order and less access time.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
// Creating an unordered_set of integers
unordered_set<int> us = {1, 2, 3, 4, 5};
for (auto x : us)
cout << x << " ";
return 0;
}
Output
5 4 3 2 1
Explanation:
In the above program, an unordered_set is initialized with the elements {1, 2, 3, 4, 5}.
- The elements are stored in a hash table internally
- The output order may differ from the insertion order
- Duplicate values, if inserted, are automatically ignored
- The exact output can vary depending on the hash implementation
Syntax
Unordered set is defined as std::unordered_set class template inside the <unordered_set> header file.
unordered_set<T> us;
Parameters
- T: represents the type of elements stored in the unordered set
- us: Name assigned to the unordered set.
Declaration and Initialization
An unordered_set can be declared and initialized in different ways, such as creating an empty container, using an initializer list, or constructing it from another container.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int main() {
// Empty unordered set
unordered_set<int> us1;
// Initialize using an initializer list
unordered_set<int> us2 = {10, 20, 30, 40};
// Initialize from a vector
vector<int> v = {1, 2, 3, 4, 5};
unordered_set<int> us3(v.begin(), v.end());
cout << "Size of us2: " << us2.size() << endl;
cout << "Size of us3: " << us3.size() << endl;
return 0;
}
Output
Size of us2: 4 Size of us3: 5
Explanation:
- unordered_set<int> us1; creates an empty unordered set
- unordered_set<int> us2 = {10, 20, 30, 40}; initializes the container using an initializer list
- unordered_set<int> us3(v.begin(), v.end()); constructs an unordered set from a range of elements in a vector
- Duplicate values, if present during initialization, are automatically removed
- The order of elements in an unordered_set is not guaranteed
Basic Operations
The unordered_set container provides several built-in functions for inserting, searching, traversing, and deleting elements efficiently.
Inserting Elements
New elements can be inserted into unordered set using insert() method. We cannot specify the position to insert the element as it is automatically decided by its hashed value.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> us;
us.insert(3);
us.insert(1);
us.insert(2);
for (auto x : us)
cout << x << " ";
return 0;
}
Output
2 1 3
Explanation
- An empty unordered set us is created
- The values 3, 1, and 2 are inserted using insert()
- The elements are traversed and printed
- The output order may vary because unordered_set does not maintain ordering
Accessing Elements
We can’t access elements of an unordered set by index like in an array or vector. We have to increment or decrement iterator obtained from begin() or end() methods respectively to access the element by position. This can also be done with the help of next() or advance() function.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> us = {1, 2, 3, 4, 5};
// Accessing third element
auto it = next(us.begin(), 2);
cout << *it;
return 0;
}
Output
5 3
Explanation
- us.begin() returns an iterator to the first element
- next(us.begin(), 2) advances the iterator by two positions
- The value pointed to by the iterator is printed
- Since the container is unordered, the accessed element may vary
Updating Elements
Elements in an unordered_set cannot be modified directly after insertion because changing a value can affect its hash.
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> us = {1, 2, 3};
// Replace 2 with 10
us.erase(2);
us.insert(10);
for (auto x : us)
cout << x << " ";
return 0;
}
Output
10 3 1
Explanation
- An unordered set us is initialized with the elements {1, 2, 3}
- us.erase(2) removes the element with value 2
- us.insert(10) inserts the new value 10 into the set
- Direct modification of elements is not allowed, so updating is performed using erase() followed by insert()
- The output order may vary because unordered_set does not maintain any specific ordering
Finding Elements
Unordered set provides fast search by value operation using the find() member function. This function returns iterator to the element if found, otherwise returns end() iterator.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> us = {1, 2, 3, 4, 5};
auto it = us.find(4);
if (it != us.end())
cout << *it;
else
cout << "Element not Found!";
return 0;
}
Output
4
Explanation
- The unordered set is initialized with five elements
- find(4) searches for the value 4
- The returned iterator is compared with end()
- Since the element exists, its value is printed
Traversing Elements
Unordered set can be traverse either range-based for loop or using begin() and end() iterator in a loop.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> us = {1, 2, 3, 4, 5};
for (auto it = us.begin(); it != us.end(); it++)
cout << *it << " ";
return 0;
}
Output
5 4 3 2 1
Explanation
- The loop starts from begin() and continues until end()
- Each element is accessed through the iterator
- The dereference operator * retrieves the value
- Elements are printed in an unspecified order
Deleting Elements
Elements can be removed from the unordered set using erase() method. We can erase elements either by value or by position.
#include <iostream>
#include <unordered_set>
using namespace std;
int main(){
unordered_set<int> us = {1, 2, 3, 4, 5};
// Delete element by value
us.erase(5);
// Delete element by position
us.erase(us.begin());
for (auto x : us)
cout << x << " ";
return 0;
}
Output
2 3 4
Explanation
- us.erase(5) removes the element with value 5
- us.erase(us.begin()) removes the element pointed to by the iterator
- The remaining elements are traversed and displayed
- The output order may vary because the container is unordered
Other Basic Operations
Unordered set is used in many situations for different purposes.
- Check if Unordered Set is Empty
- Find the Size of Unordered Set
- Swap Two Unordered Set
- Create Unordered Set for User Defined Data type
Internal Working
An unordered_set stores elements using a hash table. When an element is inserted, a hash function computes its hash value and determines the bucket where the element will be stored.
- Elements are organized into buckets based on their hash values
- Duplicate elements are not allowed and are automatically ignored
- Insertion, deletion, and search operations have an average time complexity of O(1)
- In the worst case, these operations can take O(n) time due to hash collisions
Unordered Set vs Set
Both set and unordered_set store unique elements, but they differ in how elements are organized and accessed.
| Feature | unordered_set | set |
|---|---|---|
| Internal Structure | Hash Table | Self-Balancing Binary Search Tree |
| Element Order | No specific order | Sorted order |
| Insertion | O(1) average | O(log n) |
| Deletion | O(1) average | O(log n) |
| Search | O(1) average | O(log n) |
| Duplicate Elements | Not Allowed | Not Allowed |
| Iterator Traversal | Unordered | Sorted |
Commonly Used Member Functions of Unordered Set
The unordered_set container provides several member functions for inserting, accessing, searching, and managing elements efficiently.
Function | Description |
|---|---|
| Insert a new element in the unordered set. | |
| Return an iterator pointing to the first element in the unordered set. | |
| Return an iterator pointing to beyond the element in the unordered set | |
| Count occurrences of a particular element in an unordered set. | |
| Search for an element in the unordered set. | |
| Removes all of the elements from an unordered set and empties it. | |
| Remove either a single element or a range of elements ranging from start(inclusive) to end(exclusive). | |
| Return the number of elements in the unordered set. | |
| Exchange values of two unordered set. | |
| Insert an element in an unordered set. | |
| Returns maximum number of elements that an unordered set can hold. | |
| Check if an unordered set is empty or not. | |
| This hash function is a unary function that takes a single argument only and returns a unique value of type size_t based on it. | |
| Used to request a capacity change of unordered set. | |
| Returns the current load factor in the unordered set. | |
| Set the number of buckets in the container of unordered set to a given size or more. |