Unordered Set In C++ - C++ Programming Tutorial
C++ Course / STL Set & Map / Unordered Set In C++

Unordered Set In C++

BLUF: Mastering Unordered Set In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Unordered Set In C++

C++ is renowned for its efficiency. Learn how Unordered Set In C++ enables low-level control and high-performance computing in the tutorial below.

Overview

In C++, an unordered set serves as a container data structure designed to store elements regardless of their sequence. This guide delves into multiple aspects such as the definition of an unordered set, the process of establishing and initializing it in C++, and the distinctions between an unordered set and a set in the C++ language. Exploring diverse examples and code snippets will provide a comprehensive understanding of the functionality and usage of an unordered set in C++.

What does C++'s Unordered set mean?

Introduction

In C++, an unordered set is akin to a container data structure, allowing for versatile storage capabilities. Unlike other structures, it exclusively holds individual elements without duplicates. This means that even if a duplicate element is added, the unordered set will retain only one instance of it. Additionally, the unordered set stands out for its flexibility in storing elements in any order, distinguishing it from the C++ set, which organizes elements in ascending fashion.

Let's consider an illustration to grasp the concept of how elements are stored in an unordered set in C++. Suppose we insert the values 1, 4, 9, 2, 1, and 10 into an unordered set in C++, the unordered set would be represented as below:

Example

insert(1);
insert(4);
insert(9);
insert(2);
insert(1);
insert(10);

unordered_set: 10, 2, 1, 9, 4

As evident, the duplicate of element 1 has been removed, and the elements can be arranged in any order without a specific sequence.

Unordered sets prove to be extremely useful when there is a requirement to efficiently and precisely ascertain if a specific element exists at least once within a group of elements, calculate the quantity of unique components, or both. Subsequently, we will delve deeper into the intricacies of the complexity of unordered sets in C++.

How do you create an unordered set?

Now that we understand the potential applications of an unsorted collection in C++, let's explore the process of initializing one.

First and foremost, the header file unordered_set> includes the necessary library for utilizing an unordered set in C++. It is essential to include this header at the start of our function in order to work with an unordered set in C++.

Syntax:

In C++, the subsequent syntax is employed to define an unordered set without any elements:

Example

unordered_set<data_type>set_name;

The data type of the elements to be inserted into the unordered set is denoted by the data type in this scenario.

How do you initialise an unordered set?

Initializing an unordered set in C++ involves including the unordered set> header file if you want to populate it with existing elements.

Example

unordered_set<data_type>set_name = {e1, e2, e3, e4, ...};
or,
unordered_set<data_type>set_name {e1, e2, e3, e4, ...};

Both of these methods will lead to the identical result. ```

insert(1);

insert(4);

insert(9);

insert(2);

insert(1);

insert(10);

unordered_set: 10, 2, 1, 9, 4

Example

unordered_set<data_type>set_name;

unorderedset<datatype>set_name = {e1, e2, e3, e4, ...};

or,

unorderedset<datatype>set_name {e1, e2, e3, e4, ...};

Example


Let's explore a piece of C++ code related to the unordered set functionality.

include <iostream>

include <unordered_set>

using namespace std;

int main {

unordered_set<int> p1;

unordered_set<char> p2 {'p', 'q', 'r', 's'};

return 0;

}

Example


### How is C++'s internal implementation of Unordered set done?

The storage mechanism inside unordered sets in C++ involves the utilization of a hash table. Consequently, when elements are inserted into the unordered set, they are subjected to a hashing process to generate a unique hash key, which is subsequently stored within the hash table. Due to the nature of this hashing mechanism, the elements in the unordered set are stored in a random order without any specific sequence, as the hash keys are produced through a randomized approach.

It is an additional factor that the intricacy of the hash function impacts the overall complexity of the unsorted collection. While most actions on an unsorted set in C++ generally demand O(1) constant time, there is a rare scenario where they might consume O(n) time in the worst-case scenario.

### Set vs. Unordered set

A set in C++ is an extra container type that closely resembles an unordered set. The key distinction is that while an unordered set stores elements randomly without a specific order, a set organizes them in ascending order based on their values.

Since a hash map is employed to create an unsorted collection in C++, as discussed earlier, the items are maintained in a random sequence. In contrast, the C++ set utilizes a balanced tree structure, enabling it to store elements in a sorted manner.

This difference in implementation impacts the time complexity and functionality of the containers. The C++ set typically operates at O(log(n)) time complexity, whereas the unordered set operates at O(1) time complexity for all operations. However, both containers have a space complexity of O(n) based on the number of elements they hold.

### Unordered Set Methods in C++

Let's explore the various techniques that can be employed with an unsorted collection in C++, along with their syntax and computational demands.

| Method Name | Description | Syntax | Time complexity |
| --- | --- | --- | --- |
| insert() | It is utilized to add a new element to the unordered set. | set_name.insert(element); | 0(1) |
| begin() | It gives back an iterator that goes through the unordered set's first element. | set_name.begin(); | 0(1) |
| end() | An iterator to the last element of the unordered set is returned. The location following the last element of the unordered set is indicated by this iterator. | set_name.end(); | 0(1) |
| count() | In the unordered set, it is used to determine whether an element is present. If the element is present, it yields 1, otherwise it returns 0. | set_name.count(element); | 0(1) |
| size() | It is used to return the unordered set's size or the total number of new, distinctive pieces that have been added to it. | set_name.size(); | 0(1) |
| find() | The iterator pointing to a specific value in the unordered set is located and returned using this method. If the requested element cannot be located, an iterator to the end of the unordered set is returned. | set_name.find(\*itr); | 0(1) |
| empty() | It is used to determine whether or not the unordered set is empty. If the unordered set is empty, it yields 1, otherwise it returns 0. | set_name.empty() | O(1) |
| erase() | It is used to use iterators to remove a specific element or a group of elements from the unordered set. | set_name.erase(*itr); OR set_name.erase(*itr_begin, *itr_end); | 0(number of elements removed) |
| clear() | The unordered set is totally emptied using it. | set_name.clear(); | 0(number of elements) |

### How to Iterate Over an Unordered Set's Elements in C++

In C++, arrays can be traversed using indexes, while unordered sets do not have indexes. Instead, iterators in unordered sets act as pointers to the elements. By utilizing iterators, we can iterate through the unordered set and access all its elements seamlessly.

As illustrated earlier, the begin() function provides an iterator that points to the commencement of the unsorted set, where our iteration can commence. The conclusion of our iteration will be when the iterator reaches the element following the last one in the unsorted set, which is obtained using the end() function.

include <iostream>

include <unordered_set>

using namespace std;

int main {

unordered_set<int> p1 = {11,81,15,31,7,8,21};

auto itr = p1.begin;

while(itr != p1.end){

cout<<*itr<<" ";

itr++;

}

return 0;

}

Example


Output

21 8 7 31 15 81 11

Example


We cycled through the elements until we hit the end iterator, starting from the beginning of the unordered set. In C++, we can traverse through the elements of an unordered set using the method below.

## Conclusion

In C++, an unordered set serves as a container data structure designed for storing unique elements regardless of their sequence. The header file <unordered_set> includes the necessary library for working with an unordered set in C++.

A hash table is employed to establish the unordered set in C++. Operations on an unordered set in C++ generally require constant O(1) time complexity, although there are instances where they may require linear O(n) time complexity.

Set in C++ utilizes a balanced tree structure for implementation and maintains unique elements in ascending order, distinguishing it from the unordered set.

In C++, an unordered set can be interacted with through a range of functions such as insert(), begin(), end(), size(), empty(), clear(), erase(), count(), and find().

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience