Set clear() function in C++ STL

This tutorial will discuss about the set clear() function in C++ stl.

Table Of Contents

In the C++ Standard Template Library (STL), the set is a container that ensures a sorted sequence of unique elements. The clear() member function of the set container can be used to remove all elements from the set, effectively making it empty.

Syntax of set::clear() function

void clear() noexcept;

– The function doesn’t accept any parameters.

Return Value:
– The function doesn’t return any value.

The set offers a clear() function that removes all elements from the set. After invoking this function, the set’s size becomes zero, indicating that all the elements have been removed.

Example of std::clear() function

Let’s see the complete example,

#include <iostream>
#include <set>

int main()
    std::set<int> numbers = {11, 22, 33, 44, 55};

    std::cout << "Size of set: " << numbers.size() << "n";

    // Remove all elements from Set

    std::cout << "Size of set: " << numbers.size() << "n";
    return 0;


Size of set: 5
Size of set: 0

Scenarios for Exceptions and Undefined Behavior with set::clear()

  1. Thread Safety: If the set is being accessed from multiple threads, and at least one of them modifies the set (for instance, by adding or erasing elements) while another is performing a clear() operation, it might lead to race conditions or undefined behavior. Always ensure proper synchronization when accessing the set from multiple threads.

  2. Iterator Invalidation: After calling clear(), all iterators, references, and pointers related to this set become invalidated. Any further operation using these invalidated iterators can lead to undefined behavior.


Today, we learned about set clear() function in C++ stl.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top