Unordered set in C++

Unordered_set is implemented using a hash table where keys are hashed into indices of hash table, so all the operations (search, insertion, and deletion) take constant time O(1).

  • It allows to have any key type, it can be user defined(class) or predefined(primitive data type, etc.,). 
  • It can be used for a single string. 
  • It will not allow to store duplicate values, so it stores unique values.



Insert & Find - O(1)

unordered_set <string> stringset;
string key = "C++";

stringset.insert("C++");

if (stringset.find(key) == stringset.end()) { 
    cout << " Not found " << endl;
} else {
    cout << " Found " << endl;
}

Display the unordered_set / empty()

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
  unordered_set <string> fruits; // declare string
  
  cout<< fruits.empty() << endl; //check if set is empty

  fruits.insert("Apple"); //add elements to set
  fruits.insert("Banana");
  fruits.insert("Cantaloupe");

  for (auto i: fruits) // print all the elemnts in set
    cout<< i <<endl;
  
  return 0;
}

Initialisation & merge (C++17)

#include <iostream>
#include <unordered_set>
 
using namespace std;

int main()
{
    unordered_set<char>
        p{ 'C', 'B', 'B', 'A' }, 
        q{ 'E', 'D', 'E', 'C' };
 
    cout << "p: ";
    for (auto i : p) {
         cout << i << " ";
    }
    
    cout << "\nq: ";
    for (auto i : q) {
         cout << i << " ";
    }
    
    p.merge(q);

    cout << "\np.merge(q);\n";
    cout << "p: ";
    
    for (auto i : p) {
         cout << i << " ";
    }
    
    cout << "\nq: ";
    for (auto i : q) {
         cout << i << " ";
    }
}

Output 

p: A B C 
q: C D E 
p.merge(q);
p: E D A B C 
q: C 

Click here to get the program link.

Merge

  1. No elements are moved or copied, just the internal pointers are repointed. 
  2. Each element in q is inserted into p.
  3. If an element in p with the key equivalent of is element in q exists, it will not be extracted from q. 

Contains Duplicate Leetcode Problem using unordered_set

Reference

https://www.educative.io/edpresso/unordered-sets-in-cpp

https://www.geeksforgeeks.org/how-to-create-an-unordered_set-of-user-defined-class-or-struct-in-c/

//https://stackoverflow.com/questions/15869066/inserting-into-an-unordered-set-with-custom-hash-function/15869103#15869104

//https://stackoverflow.com/questions/38554083/how-can-i-use-a-c-unordered-set-for-a-custom-class



Comments