Skip to content
Related Articles

Related Articles

set::clear in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 22 Jan, 2018

Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.

set::clear()

clear() function is used to remove all the elements of the set container, thus making its size 0.

Syntax :

setname.clear()
Parameters :
No parameters are passed.
Result :
All the elements of the set are
removed ( or destroyed )

Examples:

Input  : set{1, 2, 3, 4, 5};
         set.clear();
Output : set{}

Input  : set{};
         set.clear();
Output : set{}

Errors and Exceptions



1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.




// INTEGER SET
// CPP program to illustrate
// Implementation of clear() function
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    set<int> myset{ 1, 2, 3, 4, 5 };
  
    myset.clear();
    // Set becomes empty
  
    // Printing the Set
    for (auto it = myset.begin();
         it != myset.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

No Output




// CHARACTER SET
// CPP program to illustrate
// Implementation of clear() function
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    set<char> myset{ 'A', 'b', 'd', 'e' };
  
    myset.clear();
    // Set becomes empty
  
    // Printing the Set
    for (auto it = myset.begin();
         it != myset.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

No Output

Time complexity: Linear i.e. O(n)

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :