C++

C++ Unordered Set Functions

A Set is utilized in the C++ programming language to hold the distinct values of a list and to dynamically order its items. By default, the elements of the list are organized in ascending order.

A hash table is used to construct an unordered set where the values are converted into hash table indexes to ensure that inserting a value is always randomly assigned.  The fact is that they operate well enough and normally give a constant time search operation. All functions on the unordered set usually require a constant time O(1). Although, in the worst situation, they can take up to the linear time O(n) based on the operational hash algorithm.

The unordered set may include keys of any kind, whether they are predefined or user-defined datatypes. But whenever we declare the keys of the user-defined data structures, we must therefore indicate the comparison method that is used to compare the keys.

Difference Between Set and Unordered Set

A set is an ordered collection of distinct keys. But an unordered set is a collection of keys that could be arranged in any sequence. The implementation of Set as a balanced tree structure makes it possible to retain the order of the components. Set operations have an O(log n) time complexity, but an unordered set has an O (1). Numerous methods are defined for the unordered set. But the most popular ones are the size and empty method for storage, finding the value of the key, and inserting and removing for configuration. Only the distinct keys are supported by the unordered set; for duplicate keys, an unordered multiset may be employed.

Functions Used for Unordered Sets

The unordered set has the following methods:

  • Insert(): This function adds a new item to the container.
  • End() function: It returns an iterator that points to the item after the end.
  • Count() function: It counts the number of times a specific element appears in an unordered set.
  • Find() method: It finds a component in the set.
  • Clear() function: It empties an unordered set by removing all of its components.
  • Cbegin() function: It returns a constant iterator corresponding to the first member in the unordered set.
  • Cend() function: It returns a constant iterator with the last value in the unordered set.
  • bucket_size(): In an unordered set, this function returns the total count of items that are present in a certain bucket.
  • Erase() function: It deletes from start to end whether it is only one component or a collection of items.
  • Size() function: It gives the unordered set’s item count.
  • Swap() function: It allows you to swap the data of two unordered sets.
  • Emplace() function: Adds an item using this function to an unordered set.
  • Max_size(): This function returns the most items an unordered set is capable of holding.
  • Empty() method: It checks whether an unordered set is empty.
  • Equal range: It returns a range with all items having the predetermined value as their value.
  • Hash method(): This is a unary method that only accepts one parameter and constructs its return value on a singular size_t value.
  • Reserve() function: It is utilized to demand an unordered set’s capacity to be changed.
  • Bucket() function: It returns the item’s bucket number.
  • Bucket_count() function: An unordered set’s overall number of buckets is returned by this method.
  • Load_factor(): It returns the capacity factor that is frequently employed to the unordered set.
  • Rehash() function: It increases the range of buckets in the unordered set to the defined number or greater.
  • Max_load_factor(): It returns the ultimate load capacity index that the unordered set can support.
  • Emplace_hint() function: With the use of a hint, it only adds a new item to an unordered set if the value added is distinct.
  • Key_eq() function: It provides a Boolean value based on the comparison.

The execution of different unordered functions in C++ language is covered in this article.

Example 1:

The average processing time for the find(), insert(), and erase() functions is constant. If the key is not present in the defined set, the find() method provides an iterator to the end() function; else, it returns an iterator to the key attribute.  To acquire the key by referencing the key values with the * operator, the iterator acts as a pointer to the key attributes. The following is an instance of a declaration for the find(), insert(), and iteration functions in an unordered set.

#include <bits/stdc++.h>

using namespace std;

int main()

{
    unordered_setstringS ;

    stringS.insert("I") ;
    stringS.insert("love") ;
    stringS.insert("to") ;
    stringS.insert("play") ;
    stringS.insert("badminton") ;

    string key = "like" ;

    if (stringS.find(key) == stringS.end())
        cout<< key << " to explore " <<endl<<endl ;
    else
        cout<< "explore " << key <<endl<<endl ;

    key = "badminton";
    if (stringS.find(key) == stringS.end())
        cout<< key << " to explore\n" ;
    else
        cout<< "explore " << key <<endl ;

    cout<< "\nAll required elements : ";
    unordered_set :: iterator i;
    for (i = stringS.begin(); i != stringS.end(); i++)
        cout<< (*i) <<endl;
}

We incorporate the header file <bits/stdc++.h> in the commencement of this code. Then, we enter the standard namespace as std. Then, we invoke the main() function. Within this function, we declare the unordered set. Here, we use an unordered set to arrange the elements of the sets. We pass the string as the parameter of the unordered set function. Next, we insert the different strings in the sets. We pass the numerous strings as the arguments of the insert() function. Then, we specify the value of the key by using the keyword “key”. The find() method is used in the next step. This function is applied to find the required string of the set.

We utilize the end() method to terminate the strings. This function returns the iterator whenever the key does not exist in the set. The “cout” command is applied to print the statement. Then, we initialize again a value for the “key” attribute. We find the value of an attribute in the string by using the find() function and terminate the string with the help of the end() method. We apply the “cout” statement to show the result. We iterate over the whole set and print the content of the set by using the “cout” statement. We use the unordered set method as well as declare the iterator as “i”. The “for” loop is employed.

First, we initialize a variable and then utilize the begin() function to start the specified string. Furthermore, we define the condition of the loop. The end() function is called. The value of the iterator is incremented by 1. In the end, the “cout” statement is used to show the value of the iterator.

Example 2:

In this case, we will execute a code in which we declare a list of different values, and then we find all the duplicates from that list by the use of the unordered set function.

#include <bits/stdc++.h>

using namespace std;

void printDuplicates(int a[], int b)

{

    unordered_setintSet;
    unordered_setduplicate;

    for (int j = 0; j < b; j++)
    {

        if (intSet.find(a[j]) == intSet.end())
            intSet.insert(a[j]);

        else
            duplicate.insert(a[j]);
    }

    cout<< "The list of duplicated elements: ";
    unordered_set :: iterator it;

    for (it = duplicate.begin(); it != duplicate.end(); it++)
        cout<< *it << " ";
}

int main()
{
    int a[] = {11, 30, 42, 21, 94, 35, 11, 77, 62, 89, 94, 35};
    int b = sizeof(a) / sizeof(int);

    printDuplicates(a, b);
    return 0;
}

Here, we include the <bits/stdc++.h> library. In the next step, we utilize the standard namespace as std. We use the print() method to show the replicate in the defined array by the use of an unordered set. We provide an array and a variable to strore the integer as the arguments of the printDuplicates() method.

Now, we declare the unordered sets to acquire and save the duplicates. The unordered set function is used. We pass the integer as its parameter. Then, we utilize another unordered set function to find the duplicate elements. Here, we apply the “for” loop. We declare a variable of the “for” loop. Then, we specify the condition. Next, we increase the value “j”. We call the find() function to find the defined element in the array. We pass the specific element as the argument of this function. If the required item is already present in the array, we insert that item into the duplicate set.

We show the duplicated values of the array by using the “cout” statement. We declare the variable “it” of the iterator for the unordered set. The “for” loop is applied. Then, the begin() and end() methods are used within the “for” loop. After that, we call the main() function. We initialize a variable “a”. Then, we define the elements for the array and this array is stored in a variable “a”. We find the size of the required array by using the sizeof() method. We pass the array as the parameter of this function.

We divide the resultant value by the size of the integers. The value that we get after dividing is stored in a variable “b”. We display the duplicate values of the array with the help of the printDuplicate() method. In the end, we employ the “return 0” command.

Example 3:

A data item can be added to the unordered set container using the inbuilt C++ Standard Template Library function – the insert() function. Each item in an unordered set has a particular value and is only added if it is unavailable in the set. Since the container employs several hashing methods, the insertion is carried out automatically at the point that optimally fulfills the requirement. As a result, the container’s size is considerably enhanced by the number of retrieved items.

Parameters of Insert() Method: 

  • Value: It defines the value that should be added to the container.
  • First, last: Iterators that provide a variety of components. Note that the range encompasses all components between the first element and the last element, such as the one specified by the first element but terminates the item pointed to by the last element.

The method returns a pair, having the pair::first configured to an iterator referring to the new updated item or the corresponding component already present in the set. If a new data item is added, the pair::second component in the pair is adjusted to true; otherwise, it is specified as false if an identical item is already present.

The following program demonstrates the aforementioned function:

#include<iostream>

#include <string>

#include <unordered_set>

using namespace std;

int main()

{
    unordered_set Set = { "monday", "tuesday" };

    string str = "wednesday";
   
    Set.insert(str);

    cout<< "The set of week days is:"
        <<endl;
    for (const string&m : Set) {
        cout<< m
            << " ";
    }

    cout<<endl;
    return 0;
}

First of all, we integrate the required header files. The <iostream> is responsible for the input and output functionalities. The header file <string> contains the declaration of the strings. The third one <unordered_set> holds all the unordered sets. We utilize the standard namespace as std. Then, we start the coding inside the body of the main() function after calling the main() function. We utilize the unordered set of strings.

Here, we define the elements of my set. We specify the two days of the week. Now, we indicate the value of the string which we want to be inserted in the required set. We insert that string by using the insert() method. The “cout” statement is employed to show the text “The set of weekdays is”. We use the “cout” statement once again before entering the “return 0” command. This “cout” statement prints all the names of the weekdays.

Conclusion

The use of the C++ unordered set functions is covered in this article. We implemented the several codes on DevC++ software where we utilized many functions related to the unordered sets. Unordered sets are data structures that can hold different components in any order and provide an efficient access to specific items based on their value. In the first instance, we utilized the multiple unordered set functions to examine how the code works. Using the find() method, we identified a certain element within the set. With the help of the end() function, we terminated the unordered set. In the second illustration, we constructed an array containing various integers. Both repeated and non-repeated values are included in the array.  To find the duplicate values in the specified array, we applied the find() method. The insert() method was used in the last example to add a value to the required unordered set.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.