unordered_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:
CPP
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set< int > sampleSet;
sampleSet.insert(5);
sampleSet.insert(10);
sampleSet.insert(15);
sampleSet.insert(20);
sampleSet.insert(25);
cout << "sampleSet contains: " ;
for ( auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
cout << *itr << " " ;
}
sampleSet.clear();
cout << "\nSize of set after clearing elements: "
<< sampleSet.size();
return 0;
}
|
Output
sampleSet contains: 25 20 15 5 10
Size of set after clearing elements: 0
Program 2:
CPP
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> sampleSet;
sampleSet.insert( "Welcome" );
sampleSet.insert( "To" );
sampleSet.insert( "GeeksforGeeks" );
sampleSet.insert( "Computer Science Portal" );
sampleSet.insert( "For Geeks" );
cout << "sampleSet contains: " ;
for ( auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
cout << *itr << " " ;
}
sampleSet.clear();
cout << "\nSize of set after clearing elements: "
<< sampleSet.size();
return 0;
}
|
Output
sampleSet contains: For Geeks GeeksforGeeks Computer Science Portal Welcome To
Size of set after clearing elements: 0
Time complexity – Linear O(N)
Last Updated :
28 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...