set::clear in C++ STL

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

No Output
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

No Output

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.