Standard Template Library: Using the unordered_set

What is it?

C++ STL unordered_set is an associative container that stores unique elements in no particular order. The elements are hashed using a hash function to store them in the container and allow for fast access to individual elements. Unlike set, unordered_set does not store elements in sorted order.


Syntax

The syntax of creating an unordered_set is:

std::unordered_set<type> set_name;

Where,

  • type: It is the data type of the elements to be stored.
  • set_name: It is the name of the unordered_set.



How to use it

To use the unordered_set, follow the below steps:

  1. Include the <unordered_set> header file.
  2. Create an unordered_set container and add elements to it using insert() method.
  3. Access elements using the find() or at() method.
  4. Use the erase() method to remove elements from the container.



Program code snippet example

#include <iostream>
#include <unordered_set>

using namespace std;

int main() {

   // Creating an unordered_set and adding elements to it.
   unordered_set<int> mySet;
   mySet.insert(10);
   mySet.insert(20);
   mySet.insert(30);
   mySet.insert(40);
   mySet.insert(50);

   // Accessing elements using find() method.
   auto it = mySet.find(30);
   if (it != mySet.end()) {
      cout << "Element found: " << *it << endl;
   } else {
      cout << "Element not found" << endl;
   }

   // Accessing elements using at() method.
   try {
      int value = mySet.at(2);
      cout << "Value at index 2: " << value << endl;
   } catch (const out_of_range& e) {
      cout << "Exception: " << e.what() << endl;
   }

   // Removing elements from the unordered_set.
   mySet.erase(40);

   // Printing all elements in the unordered_set.
   for (auto x : mySet) {
      cout << x << " ";
   }

   return 0;
}

Output:

Element found: 30
Exception: unordered_set::at: key not found
10 50 20 30




You are given a list of integers. Print the unique integers in the list in sorted order. You must use the unordered_set container to filter the duplicates. It would be best to use the vector container to store the unique integers before sorting and printing them.