unoredered_set clear() function in C++ STL

The unordered_set::clear() function is a built-in function in C++ STL which is used to clear an unordered_set container. That is, this function removes all of the elements from an unordered_set and empties it. All of the iterators, pointers, and references to the container are invalidated. This reduces the size of the container to zero.

Syntax:

unordered_set_name.clear()

Parameter: This function does not accepts any parameter.

Return Value: This function does not returns any value.

Below programs illustrate the unordered_set::clear() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unordered_set::clear() function
  
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<int> sampleSet;
  
    // Inserting elements
    sampleSet.insert(5);
    sampleSet.insert(10);
    sampleSet.insert(15);
    sampleSet.insert(20);
    sampleSet.insert(25);
  
    // displaying all elements of sampleSet
    cout << "sampleSet contains: ";
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
        cout << *itr << " ";
    }
  
    // clear the set
    sampleSet.clear();
  
    // size after clearing
    cout << "\nSize of set after clearing elemets: "
         << sampleSet.size();
  
    return 0;
}

chevron_right


Output:

sampleSet contains: 25 5 10 15 20 
Size of set after clearing elemets: 0

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unordered_set::clear() function
  
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<string> sampleSet;
  
    // Inserting elements
    sampleSet.insert("Welcome");
    sampleSet.insert("To");
    sampleSet.insert("GeeksforGeeks");
    sampleSet.insert("Computer Science Portal");
    sampleSet.insert("For Geeks");
  
    // displaying all elements of sampleSet
    cout << "sampleSet contains: ";
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
        cout << *itr << " ";
    }
  
    // clear the set
    sampleSet.clear();
  
    // size after clearing
    cout << "\nSize of set after clearing elemets: "
         << sampleSet.size();
  
    return 0;
}

chevron_right


Output:

sampleSet contains: Welcome To GeeksforGeeks For Geeks Computer Science Portal 
Size of set after clearing elemets: 0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.