C++ Standard Library C++ STL Library

C++ unordered_set - operator== Function



The C++ unordered_set operator== function is used to check whether two unordered_sets are equal or not. It returns true if two unordered_sets are equal, else returns false. operator== first checks the size of both unordered_sets, if sizes are same then it compares elements of unordered_sets and stops comparison after first mismatch.

Syntax

template <class Key, class Hash, class Pred, class Alloc>
bool operator== (const unordered_set<Key,Hash,Pred,Alloc>& lhs, 
                 const unordered_set<Key,Hash,Pred,Alloc>& rhs);

Parameters

lhs First unordered_set.
rhs Second unordered_set.

Return Value

Returns true if the contents of lhs are equal to the contents of rhs, else returns false.

Time Complexity

Average Case: Linear i.e, Θ(n).
Worst Case: Quadratic i.e, Θ(n²).

Example:

In the example below, the operator== function is used to check whether two unordered_sets are equal or not.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet1 {10, 20, 30, 100, 30};
  unordered_set<int> uSet2 {10, 20, 100, 30};
  unordered_set<int> uSet3 {10, 20, 30, 500};

  if (uSet1 == uSet2)
    cout<<"uSet1 and uSet2 are equal.\n";
  else
    cout<<"uSet1 and uSet2 are not equal.\n";

  if (uSet1 == uSet3)
    cout<<"uSet1 and uSet3 are equal.\n";
  else
    cout<<"uSet1 and uSet3 are not equal.\n";
    
  return 0;
}

The output of the above code will be:

uSet1 and uSet2 are equal.
uSet1 and uSet3 are not equal.

❮ C++ <unordered_set> Library