Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ unordered_set::clear function is used to clear all elements of the unordered_set. This function makes the unordered_set empty with a size of zero.

Syntax

void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

In the below example, the unordered_set::clear function is used to clear all elements of the unordered_set called uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{10, 20, 30, 40, 50};
  unordered_set<int>::iterator it;

  cout<<"Before clear() function: \nThe unordered_set is:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nUnordered Set size is: "<<uSet.size()<<"\n\n";

  uSet.clear();

  cout<<"After clear() function: \nThe unordered_set is:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nUnordered Set size is: "<<uSet.size()<<"\n\n";
  return 0;
}

The output of the above code will be:

Before clear() function: 
The unordered_set is: 50 40 30 20 10
Unordered Set size is: 5

After clear() function: 
The unordered_set is:
Unordered Set size is: 0

❮ C++ - Unordered Set