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;
Parameters:
– 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,
Frequently Asked:
#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 numbers.clear(); std::cout << "Size of set: " << numbers.size() << "n"; return 0; }
Output
Pointers in C/C++ [Full Course]
Size of set: 5 Size of set: 0
Scenarios for Exceptions and Undefined Behavior with set::clear()
-
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.
-
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.
Summary
Today, we learned about set clear() function in C++ stl.