How to Check if a Set is Empty in C++?
In C++, a set is an associative container that stores unique elements in a sorted order. In this article, we’ll explore different approaches to check if a set is empty in C++ STL.
Check if a Set is Empty or Not in C++
To check if a std::set is empty in C++, we can use the std::set::empty() function. This function returns a boolean value indicating whether the set is empty.
C++ Program to Check if a Set is Empty
C++
// C++ Program to show how to check if a set is empty or not #include <iostream> #include <set> using namespace std; int main() { // Creating sets named 'mySet1' and 'mySet2' set< int > mySet1; set< int > mySet2 = { 1, 2 }; // Checking if mySet1 is empty if (mySet1.empty()) { cout << "Set1 is empty." << endl; } else { cout << "Set1 is not empty." << endl; } // Checking if mySet1 is empty if (mySet2.empty()) { cout << "Set2 is empty." << endl; } else { cout << "Set2 is not empty." << endl; } return 0; } // This code is contributed by Susobhan Akhuli |
Output
Set1 is empty. Set2 is not empty.
Time Complexity: O(1)
Auxiliary Space: O(1)
The set container in C++ STL provides an size() member function that returns the size (or number of elements) of the set. We can also check is a set is empty or not using size() function in C++ because if the size is 0, then the set is empty otherwise not.
Contact Us