×

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

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.