The C++ std::unordered_set::clear() function is used to erase all the elements from the unordered_set container. This function doesn't make any changes if the current unordered_set is empty otherwise, it will erase all the elements from the unordered_set. when this function is invoked the size() function return a zero. The return type of this function is void, which implies that it does not return any value.
SyntaxFollowing is the syntax of the C++ std::unordered_set::clear() function −
void clear();Parameters
This function does not return any value.
Example 1Let's look at the following example, where we are going to use the clear() function and observing the output.
#include<iostream> #include<string> #include<unordered_set> using namespace std; int main () { //create a unordered_set unordered_set<int> u_set = {1, 2, 3, 4, 5}; cout<<"Contents of the u_set before the clear operation are: "<<endl; for(int n : u_set){ cout<<n<<endl; } //using the clear() function u_set.clear(); cout<<"Size of the u_set after the clear operation: "<<u_set.size(); }Output
If we run the above code it will generate the following output −
Contents of the u_set before the clear operation are: 5 4 3 2 1 Size of the u_set after the clear operation: 0Example 2
Consider another scenario, where we are going to use the cler() function the unordered_set of type char.
#include<iostream> #include<string> #include<unordered_set> using namespace std; int main () { //create a unordered_set unordered_set<char> char_set = {'A', 'B', 'C', 'D', 'E'}; cout<<"Contents of the char_set before the clear operation are: "<<endl; for(char c : char_set){ cout<<c<<endl; } //using the clear() function char_set.clear(); cout<<"Size of the char_set after the clear operation: "<<char_set.size(); }Output
Following is the output of the above code −
Contents of the char_set before the clear operation are: E D C B A Size of the char_set after the clear operation: 0Example 3
Following is the another example of using the clear() function on the unordered_set of the type string.
#include<iostream> #include<string> #include<unordered_set> using namespace std; int main () { //create a unordered_set unordered_set<string> str_set = {"Rahul", "Mukesh", "Dinesh", "Raja"}; cout<<"Contents of the str_set before the clear operation are: "<<endl; for(string s : str_set){ cout<<s<<endl; } //using the clear() function str_set.clear(); cout<<"Size of the str_set after the clear operation: "<<str_set.size(); }Output
Output of the above code is as follows −
Contents of the str_set before the clear operation are: Dinesh Mukesh Raja Rahul Size of the str_set after the clear operation: 0
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4