C++ Standard Library C++ STL Library

C++ unordered_set - clear() Function



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 example below, 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 contains:";
  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 contains:";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nUnordered Set size is: "<<uSet.size();
  return 0;
}

The output of the above code will be:

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

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

❮ C++ <unordered_set> Library