The Wayback Machine - https://web.archive.org/web/20240827184513/https://www.geeksforgeeks.org/unordered_set-in-cpp-stl/
Open In App

Unordered Sets in C++ Standard Template Library

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An unordered_set is an unordered associative container implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set take constant time O(1) on an average which can go up to linear time O(n) in the worst case which depends on the internally used hash function, but practically they perform very well and generally provide a constant time lookup operation. 
 
The unordered_set can contain a key of any type – predefined or user-defined data structure but all the keys must be unique. It is defined inside <unordered_set> header file as std::unordered_set class.

Syntax:

std::unordered_set<data_type> name;

In std::unordered_set, many functions are defined among which the most used functions are:

  • The size() and empty() for capacity.
  • The find() for searching a key.
  • The insert () and erase() for modification.

Example:

C++
// C++ program to demonstrate various function of
// unordered_set
#include <bits/stdc++.h>
using namespace std;

int main()
{
    // declaring set for storing string data-type
    unordered_set<string> stringSet;

    // inserting various string, same string will be stored
    // once in set

    stringSet.insert("code");
    stringSet.insert("in");
    stringSet.insert("c++");
    stringSet.insert("is");
    stringSet.insert("fast");

    string key = "slow";

    // find returns end iterator if key is not found,
    // else it returns iterator to that key

    if (stringSet.find(key) == stringSet.end())
        cout << key << " not found" << endl << endl;
    else
        cout << "Found " << key << endl << endl;

    key = "c++";
    if (stringSet.find(key) == stringSet.end())
        cout << key << " not found\n";
    else
        cout << "Found " << key << endl;

    // now iterating over whole set and printing its
    // content
    cout << "\nAll elements : ";
    unordered_set<string>::iterator itr;
    for (itr = stringSet.begin(); itr != stringSet.end();
         itr++)
        cout << (*itr) << endl;
}

Output
slow not found

Found c++

All elements : is
fast
c++
in
code

The functions find(), insert() and erase() take a constant amount of time on average. The find() function returns an iterator to end() if a key is not there in the set, otherwise, an iterator to the key position is returned. The iterator works as a pointer to the key values so that we can get the key by dereferencing them using the * operator.

We can also see that the order of output is messed up because there is no particular order to store data in unordered_set.

Note: The Unordered_set allows only unique keys, for duplicate keys unordered_multiset should be used.

set vs unordered_set in C++ STL

Set

Unordered Set

A Set is an ordered sequence of unique keys.An unordered_set is a set in which a key can be stored in any order, so unordered.
Set is implemented as a balanced tree structure making it possible to maintain order between the elements (by specific tree traversal).The unordered_set is implemented as hash tables as we don’t have to worry about any order.
The time complexity of set operations is O(log n).The time complexity of basic set operations is O(1).(Average Case)
For worst case time complexity is O(n).

A practical problem based on unordered_set

Given an array(list) of integers, find all the duplicates among them(suppose the duplicates are the same number guessed by random people in an experiment).

Input:

arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5}

Output:

Duplicate items are: 5 2 1 

Example:

C++
// C++ program to find duplicate from an array using
// unordered_set
#include <bits/stdc++.h>
using namespace std;

// Print duplicates in arr[0..n-1] using unordered_set
void printDuplicates(int arr[], int n)
{
    // declaring unordered sets for checking and storing
    // duplicates
    unordered_set<int> intSet;
    unordered_set<int> duplicate;

    // looping through array elements
    for (int i = 0; i < n; i++) {
        // if element is not there then insert that
        if (intSet.find(arr[i]) == intSet.end())
            intSet.insert(arr[i]);

        // if element is already there then insert into
        // duplicate set
        else
            duplicate.insert(arr[i]);
    }

    // printing the result
    cout << "Duplicate item are : ";
    unordered_set<int>::iterator itr;

    // iterator itr loops from begin() till end()
    for (itr = duplicate.begin(); itr != duplicate.end();
         itr++)
        cout << *itr << " ";
}

// Driver code
int main()
{
    int arr[] = { 1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5 };
    int n = sizeof(arr) / sizeof(int);

    printDuplicates(arr, n);
    return 0;
}

Output
Duplicate item are : 5 2 1 


Time Complexity: O(n log n)
Auxiliary Space: O(n)

std::unordered_set Member Methods

The following table contains all the member functions of std::unordered_set class:

Function Name

Function Description

insert()

Insert a new {element} in the unordered_set container.

begin()

Return an iterator pointing to the first element in the unordered_set container.

end()

Returns an iterator pointing to the past-the-end-element.

count()

Count occurrences of a particular element in an unordered_set container.

find()

Search for an element in the container.

clear()

Removes all of the elements from an unordered_set and empties it.

cbegin()

Return a const_iterator pointing to the first element in the unordered_set container.

cend()

Return a const_iterator pointing to a past-the-end element in the unordered_set container or in one of its buckets.

bucket_size()

Returns the total number of elements present in a specific bucket in an unordered_set container.

erase()

Remove either a single element or a range of elements ranging from start(inclusive) to end(exclusive).

size()

Return the number of elements in the unordered_set container.

swap()

Exchange values of two unordered_set containers.

emplace()

Insert an element in an unordered_set container.

max_size()

Returns maximum number of elements that an unordered_set container can hold.

empty()

Check if an unordered_set container is empty or not.

equal_range

Returns range that includes all elements equal to a given value.

operator=

Copies (or moves) an unordered_set to another unordered_set and unordered_set::operator= is the corresponding operator function.

hash_function()

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.

reserve()

Used to request a capacity change of unordered_set.

bucket()

Returns the bucket number of a specific element.

bucket_count()

Returns the total number of buckets present in an unordered_set container.

load_factor()

Returns the current load factor in the unordered_set container.

rehash()

Set the number of buckets in the container of unordered_set to a given size or more.

max_load_factor()

Returns(Or sets) the current maximum load factor of the unordered set container.

emplace_hint()

Inserts a new element in the unordered_set only if the value to be inserted is unique, with a given hint.

== operator 

The ‘==’ is an operator in C++ STL that performs an equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same.

key_eq()

Returns a boolean value according to the comparison. It returns the key equivalence comparison predicate used by the unordered_set.

operator!=

The != is a relational operator in C++ STL which compares the equality and inequality between unordered_set containers.

max_bucket_count() 

Find the maximum number of buckets that unordered_set can have.

Must Read – Recent Articles on unordered_set



Similar Reads

The C++ Standard Template Library (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequ
5 min read
Sort in C++ Standard Template Library (STL)
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By defa
6 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Binary Search in C++ Standard Template Library (STL)
Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. The main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the element is found, or all the elements are exhausted.It works by comparing the middle item of the array with our target, if it match
3 min read
Multimap in C++ Standard Template Library (STL)
Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always. These properties of multimap make it very much useful i
6 min read
Queue in C++ Standard Template Library (STL)
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its eleme
3 min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Pair in C++ Standard Template Library (STL)
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in &lt;utility&gt; header consisting of two data elements or objects. The first element is referen
9 min read
List in C++ Standard Template Library (STL)
Lists are sequence containers that allow non-contiguous memory allocation. As compared to the vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick (constant time). Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward_list. std::
6 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the &lt;set&gt; header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
Multiset in C++ Standard Template Library (STL)
Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() - Returns an iterator to the first element in the multiset --&gt; O(1)end() - Returns an iterator to the theoretical element that follows the last element in th
6 min read
Difference Between STL and Standard Library in C++
In C++, the term "Standard Library" and "Standard Template Library" are often misinterpreted as the same. Although they sound same with only a single word difference, they refer to the different part of the C++ programming language. In this article, we will learn what's the difference between the C++ Standard Library and Standard Template Library (
3 min read
Vector of Unordered Maps in C++ with Examples
Vector: Vector: It is the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. Some of the functions used with vector:
6 min read
Forward List and List of Unordered Maps in C++ with Examples
Forward List Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only
10 min read
unordered set of tuples in C++ with Examples
What is a tuple? A tuple in C++ is an object which is used to group elements together. In a tuple, elements can be of the same data type or different data types. The elements of tuples are initialized as in the order in which they will be accessed. Functions associated with a tuple: 1. make_tuple(): make_tuple() is used to assign tuple with values.
6 min read
unordered set of Pairs in C++ with Examples
What is pair? Utility header in C++ provides us pair container. A pair consists of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneou
5 min read
unordered set of Vectors in C++ with Examples
What is an unordered set? In C++, an unordered set is an unordered container that can hold a number of unique elements. Unlike a set, elements in an unordered set are not arranged in any particular order. Internally, an unordered set is implemented using a hash table where keys are hashed into indices of a hash table that is why the insertion is al
6 min read
Array of unordered maps in C++ with Examples
What is an array? An array in any programming language is a data structure that is used to store elements or data items of similar data types at contiguous memory locations and elements can be accessed randomly using indices of an array. Arrays are efficient when we want to store a large number of elements that too of similar data types. What is Un
5 min read
max_bucket_count() Function in Unordered Set C++ STL
Prerequisite: unordered_set() in C++ The max_bucket_count() is the built-in function defined in C++ STL. This function returns the maximum number of buckets that the Unordered Set is able to hold. Syntax: unordered_set.max_bucket_count(); Parameters: It does not accept any parameter. Return Type: Returns the maximum number of buckets. Time Complexi
2 min read
Opening Modes in Standard I/O in C/C++ with Examples
Pre-requisites: File Handling in C++ So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be perfo
13 min read
C++ 03 Standard
The C++ programming language, initially developed by Bjarne Stroustrup in 1983, quickly became one of the most popular programming languages due to its efficiency, flexibility, and support for object-oriented programming. However, as the language evolved, variations and extensions introduced by different compiler vendors led to compatibility issues
4 min read
C++ 23 Standard
C++23, officially known as ISO/IEC 14882:2023, is the latest standardized version of the C++ programming language, published in 2023. As C++ introduces new improvements and features every 3 years in the form of a standard like C++20 introduced powerful features such as concepts, ranges, and coroutines, marking a substantial leap in expressiveness a
6 min read
Why are Standard Iterator Ranges [begin, end) Instead of [begin, end]?
In C++, the Standard Template Library (STL) uses a half-open range convention [begin, end) for iterator ranges. This means the range includes the begin iterator but excludes the end iterator. A common question arises: Why does the STL adopt this convention instead of the fully closed range [begin, end]? In this article, we will learn the advantages
4 min read
What are the Complexity Guarantees of the Standard Containers?
In C++, the Standard Template Library (STL) provides various containers such as std::vector, std::list, std::map, and others, each designed for specific use cases. A very important aspect when we choose the right container for our application is to understand the complexity guarantees they offer for various operations. These guarantees allow us to
3 min read
C++ 11 Standard
C++ 11, officially known as ISO/IEC 14882:2011, is a significant version of the C++ programming language standard, published in 2011. It marked a major fix up of the language, introducing various features and enhancements that improved the usability, performance, and safety of C++ code. Before C++ 11, C++ 03 was the standard, and while it solidifie
5 min read
C++ 98 Standard
C++ 98, officially known as ISO/IEC 14882:1998, was the first international standard for the C++ programming language, published in 1998. This version standardized features that were already widely used in the C++ community and also introduced some new features that laid the foundation for future advancements in the language. Before C++ 98, C++ was
4 min read
Equally divide into two sets such that one set has maximum distinct elements
There are two processes P1 and P2, and N resources where N is an even number. There is an array of N size and arr[i] represents the type of ith resource.There may be more than one instance of a resource.You are to divide these resources equally between P1 and P2 such that maximum number of distinct number of resources are allocated to P2. Print max
8 min read
Map of Sets in C++ STL with Examples
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it i
2 min read