Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Unorderd_set in C++
3.
Initialization of Unordered Sets
4.
Functions on Unordered set
5.
Iterator in Unordered_set
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Unordered_set in C++

Author Tanay Kumar
2 upvotes
gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

The C++ STL (Standard Template Library) supports several data structures that play a crucial role in solving any problem. One such data container is the "Unordered_set in C++". Unlike the sets in  STL, this type of set is unordered in its way of storing elements.

To learn more about C++ STL visit the C++ guided path.

This article will discuss unordered_set in c++ and its different methods for performing operations.

Unorderd_set in C++

Unordered_set in C++ is an associative container containing a set of unique objects of the Key type. Search, removal, and insertion have an average time complexity of O(1).

Internally, the elements in an unordered_set in C++ are not sorted in any order but are organized into buckets. Which element will be placed in which bucket entirely depends on the hash of its value. It allows fast access of individual elements since once the hash is computed, it refers to the same bucket the element is placed into.

The properties of unordered_set in C++ STL is as follows:

  • Uniqueness: Every element in an unordered set is unique.
  • Unindexed: The elements inside an unordered set can not be indexed by position.
  • Immutable: We cannot change or modify the elements in unordered sets.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Initialization of Unordered Sets

We can initialize an unordered_set in multiple ways in C++. Let’s see those methods with the below example.

#include<bits/stdc++.h>
using namespace std;
 
 
int main(){
 
    // Method 1
    // Initialize an empty unordered set of integer type
    unordered_set<int> s1;
 
    // Method 2   
    // Initializing a Hard-coded unordered set
    unordered_set<int> s2 = {1, 4, 5, 3, 2};
 
    // Method 3
    // IAn Unordered set using another unordered set
    unordered_set<int> s4(s2);
    // s4 = {1, 4, 5, 3, 2}
 
    // Method 4
    // An unordered set using arrays
    int arr[] = {6, 2, 3, 5, 1};
    unordered_set<int> s5(arr, arr+3);
    // s4 = {3, 2, 6} 
}

 

We have initialized unordered sets using four different methods where,

  • Method 1: We have initialized an empty unordered set of integer types.
  • Method 2: We have initialized an unordered set of integer types by hardcoding.
  • Method 3: We have initialized an unordered set using another unordered set.
  • Method 4: We have initialized an unordered set using an array. It stores the elements in reverse order.


You can also practice with the help of Online C++ Compiler

Functions on Unordered set

For an unordered set, many functions or methods are defined, among which the most used ones are the empty and size for capacity, find for searching a key, erase and insert for modification.

Now let's learn about them in brief with the below table:

Function

Description

insert() We use it to insert a new element in the unordered_set container.
begin() It returns an iterator to the first element in the unordered_set container.
end() It returns an iterator to the end of the unordered_set.
count() It counts the occurrences of any particular element in an unordered_set.
find() It searches for an element in the container.
clear() It removes all of the elements from the unordered_set and empties it.
erase() It removes either a single element or a range of elements from the start(inclusive) to end(exclusive).
size() It returns the number of elements in an unordered_set container.
swap() It swaps the contents of two unordered sets.
empty() It checks if the unordered_set is empty or not.
emplace(value) It inserts the value passed as an argument into the set.

Let's consider an example of declaration, insert, find, and iteration in an unordered set.

// C++ program to demonstrate various function of unordered_set
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Declaring unordered set for string data-type
    unordered_set <string> stringSet ;
 
    // Inserting various strings in the set 
    stringSet.insert("code") ;
    stringSet.insert("in") ;
    stringSet.insert("c++") ;
    stringSet.insert("is") ;
    stringSet.insert("fast") ;
 
    string key = "slow" ;
 
    //  Find returns an iterator to the key,
    //  Else it returns end iterator if the key is not found
 
    if (stringSet.find(key) == stringSet.end())
        cout << key << " not found" << endl;
    else
        cout << "Found " << key << endl ;
 
    key = "fast";
    if (stringSet.find(key) == stringSet.end())
        cout << key << " not found"<<endl ;
    else
        cout << "Found " << key << endl ;
 
    // Now iterating over complete set and printing its content
    cout << "All elements : "<<endl;


    // Initializing an iterator to the unordered set
    unordered_set<string> :: iterator itr;
    for (itr = stringSet.begin(); itr != stringSet.end(); itr++)
        cout << (*itr) << " ";
}

 

The output for the above code is displayed below:

Output

Iterator in Unordered_set

An iterator to an unordered_set is an object (like a pointer) pointing to an element inside the unordered_set container. We can use these iterators to move through the elements of the container.

Syntex:

// Initializing an iterator
unordered_set<data_type> :: iterator itr;

 

Example:

Let’s consider an example for iterating over the complete unordered_set.

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Declaring unordered set for string data-type
    unordered_set <string> stringSet ;
 
    // Inserting various strings in the set
 
    stringSet.insert("code") ;
    stringSet.insert("in") ;
    stringSet.insert("c++") ;
 
    // Now iterating over complete set and printing its content
    cout << "All elements : "<<endl;


    // Initializing an iterator to the unordered set
    unordered_set<string> :: iterator itr;
    for (itr = stringSet.begin(); itr != stringSet.end(); itr++)
        cout << (*itr) << " ";
}

 

The output of the above code after iterating through the whole set is displayed below:

Output

Read More - Time Complexity of Sorting Algorithms

FAQs

  1. What are the differences between set and unordered_set in C++?
    A set is an ordered sequence of unique keys, whereas an unordered_set is a set in which unique keys can be stored without any order, so unordered. The time complexity for set operations is O(log(n)), while for an unordered_set, it is O(1).
     
  2. What is the difference between begin(), cbegin() and end(), cend()?
    begin() and end() method returns the iterator to the beginning and end of the unordered_set in c++ whereas cbegin() and cend() returns a const_iterator to the beginning and end of the unordered_set.
     
  3. What are data types supported for the key of an unordered_set in C++?
    An unordered_set can contain a key of any type – user-defined or pre-defined data structure. Still, when we define a key of a user-defined type, we need to specify our custom comparison function according to compare the keys.
     
  4. What is the worst and average time complexity of an unordered_set in c++?
    For an unordered_set, the average time complexity is O(1), while the worst-case complexity is O(n).

Key Takeaways

In this article, we have extensively discussed Unordered_set in c++. We learned how to initialize unordered_set in c++ and its different methods.

Check out this problem - Reverse Nodes In K Group

We hope that this blog has helped you enhance your knowledge regarding different unordered_set in C++, and if you would like to learn more, check out our articles on STL containers in C++Data Types in C++, and Implementing Sets Without C++ STL Containers. Do upvote our blog to help other ninjas grow. Happy Coding!

Next article
Unordered_multiset in C++
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass