Home »
C++ STL
set::clear() function in C++ STL
C++ STL set::clear() function: Here, we are going to learn about the clear() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019
C++ STL set::clear() function
set::clear() function is a predefined function, it is used to clear the entire set irrespective of its elements.
Syntax
set<T> st; //declaration
st.clear()
Parameter(s)
This function does not accept any parameter.
Return value
This function does not return any value. The function clears the entire set irrespective of its elements.
Sample Input and Output
For a set of integer,
set<int> st;
st.insert(4);
st.insert(5);
set content:
4
5
st.clear();
set content:
empty set
Header file
Header file to be included:
#include <iostream>
#include <set>
OR
#include <bits/stdc++.h>
Example
#include <bits/stdc++.h>
using namespace std;
void printSet(set<int> st) {
set<int>::iterator it;
cout << "Set contents are:\n";
if (st.empty()) {
cout << "empty set\n";
return;
}
for (it = st.begin(); it != st.end(); it++) cout << *it << " ";
cout << endl;
}
int main() {
cout << "Example of clear function\n";
set<int> st;
set<int>::iterator it;
cout << "inserting 4\n";
st.insert(4);
cout << "inserting 6\n";
st.insert(6);
cout << "inserting 10\n";
st.insert(10);
printSet(st); // printing current set
cout << "clearing all elements\n";
st.clear();
printSet(st);
return 0;
}
Output
Example of clear function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
clearing all elements
Set contents are:
empty set