×

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of user-defined data structures, we must describe our comparison function under how keys will be compared.

Unordered set methods

Numerous functions are defined for unordered sets. The Unordered Set supports unique keys. An unordered multiset should be used for duplicate keys.

Following is an example of a declaration, find, insert, and iteration in an unordered set:

Example 1:

// A C++ program that demonstrates the unordered Set's numerous features
#include <bits/stdc++.h>
usingnamespace std;
  
int main()
{
    // setting up a set to hold the string data type
    unordered_set <string> stringSet ;
    // the identical string will be stored after each inserted line, once in a group.  
    stringSet.insert("code") ;
    stringSet.insert("in") ;
    stringSet.insert("c++") ;
    stringSet.insert("is") ;
    stringSet.insert("fast") ;
  
    string key = "slow" ;
  
    //  If the key cannot be found, find produces an end iterator.
    //  if not, an iterator to that key is returned.
  
    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 ;
  
    // presently iterating through the entire Set and outputting its content
    cout << "\nAll elements : ";
    unordered_set<string> :: iterator itr;
    for (itr = stringSet.begin(); itr != stringSet.end(); itr++)
        cout << (*str) << endl;
}

Output:

How to Declare Unordered Sets in C++

Find, insert, and erase generally take the same amount of time. Finding all the duplicates within an array (list) of integers is a real-world problem based on an unordered set.

How to Declare Unordered Sets in C++

The C++ approach utilizing unordered sets is shown below.

Example 2:

// Using a C++ application, locate duplicates in an array
Unordered Set 
#include <bits/stdc++.h>
usingnamespace std;
// Utilizing unordered set, print duplicates in arr[0..n-1]
void printDuplicates(int arr[], int n)
{
    // creating unordered collections to be used for storing and checking duplicates
    unordered_set<int> intSet;
    unordered_set<int> duplicate;
  
    // looping through the items in an array
    for (int i = 0; i < n; i++)
    {
        // if an element is missing, add it.
        if (intent.find(arr[i]) == intent.end())
            intent.insert(arr[i]);
  
       // Insert into duplicate Set if the element already exists.        
else
            duplicate.insert(arr[i]);
    }
  
    // publishing the outcome
    cout << "Duplicate item are: ";
    unordered_set<int> :: iterator itr;
  
    // From begin() to finish, iterator loops ()
    for (it = duplicate.begin(); it != duplicate.end(); itr++)
        cout << *it << " ";
}
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:

How to Declare Unordered Sets in C++

Techniques for Unordered Sets

  • Insert a new "element" into the unordered set container with insert ().
  • Return the iterator for the first element in the unordered set container with the begin() function.
  • End() produces an iterator that navigates to the piece after the end.
  • Count() function counts how many times a specific feature appears in an unordered set container.
  • Find a part in the container using the find() function.
  • Clear() Empties an unordered set by removing all its components.
  • Return the first element in the unordered set container as a const iterator with the help of the begin() function.
  • Return a const iterator pointing to an element past the end of the unordered set container or a bucket within it with the lot() function.
  • Return the overall number of elements in a particular bucket within an unordered set container.
  • Remove one element or a group of items from the start (inclusive) to the finish using the erase() function (exclusive).
  • Size() will give the container's unordered set element count.
  • Swap two unordered set containers' values with this function.
  • Add an element to an unordered set container using the emplace() method.
  • An unordered set container's maximum number of elements can be found using the max size() function.
  • Check whether an unordered set container is empty using the empty() method.
  • Returns a range containing all elements with values equal to the specified value.
  • operator= - Moves or copies an unordered set from one unordered Set to another.
  • The analogous operator function is operator=.
  • Hash function is a unary function that only accepts a single parameter and outputs a single size t value.
  • Reserve() asks for an unordered set's capacity to be changed.
  • Return the element's bucket number using the bucket() function.
  • An unordered set container's total number of buckets is returned by the bucket count() function.
  • Return the current load factor for the unordered set container through load factor().
  • Set the number of buckets in the unordered set container to the specified size or more significant with the rehash() function.
  • The maximum load factor of the unordered set container is returned or set by the max load factor() function.
  • If the value to be inserted is unique, and a hint is provided, the function emplace hint() will only add a new element to the unordered Set.
  • Operator == When two unordered sets are compared side by side using the '==' operator in the C++ STL, unordered Set:: The analogous operator function for the same is operator==.
  • Essential eq() provides a Boolean result based on the comparison. It gives back the unordered Set's necessary equivalence comparison predicate.

Related Topics

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.