Open In App

set::clear in C++ STL

Last Updated : 22 Jan, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads