C++ Standard Library C++ STL Library

C++ set - clear() Function



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

Syntax

void clear();
void clear() noexcept;

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n)

Example:

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

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

  cout<<"Before clear() function: \nThe set contains:";
  for(it = MySet.begin(); it != MySet.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nSet size is: "<<MySet.size()<<"\n\n";

  MySet.clear();

  cout<<"After clear() function: \nThe set contains:";
  for(it = MySet.begin(); it != MySet.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nSet size is: "<<MySet.size();
  return 0;
}

The output of the above code will be:

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

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

❮ C++ <set> Library