How to Check if a Set is Empty in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet1;
set< int > mySet2 = { 1, 2 };
if (mySet1.empty()) {
cout << "Set1 is empty." << endl;
}
else {
cout << "Set1 is not empty." << endl;
}
if (mySet2.empty()) {
cout << "Set2 is empty." << endl;
}
else {
cout << "Set2 is not empty." << endl;
}
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...