This tutorial will discuss how to check if multiset is empty in C++?.
Multiset in C++ provides a function called ’empty()’, which returns true if there are no elements in the multiset. For instance, if we create an empty multiset named ‘numSet’, it won’t contain any elements.
std::multiset<int> numSet;
When we call the ’empty()’ function on this multiset, it will return true.
// Check if multiset is empty if(numSet.empty()) { std::cout<< "MultiSet is empty" << std::endl; } else { std::cout<< "MultiSet is not empty" << std::endl; }
Output:
MultiSet is empty
Now, if we insert two elements into ‘numSet’ using the ‘insert’ function, and subsequently call the ’empty’ function, it will return false. This is because ‘numSet’ now contains two elements.
numSet.insert(45); numSet.insert(41); // Check if multiset is empty if(numSet.empty()) { std::cout<< "MultiSet is empty" << std::endl; } else { std::cout<< "MultiSet is not empty" << std::endl; }
Output:
MultiSet is not empty
Thus, we can use the ’empty’ member function of multiset to check whether a multiset is empty or not.
Let’s see the complete example,
#include <iostream> #include <set> int main() { std::multiset<int> numSet; // Check if multiset is empty if(numSet.empty()) { std::cout<< "MultiSet is empty" << std::endl; } else { std::cout<< "MultiSet is not empty" << std::endl; } // Insert two elements on multiset numSet.insert(45); numSet.insert(41); // Check if multiset is empty if(numSet.empty()) { std::cout<< "MultiSet is empty" << std::endl; } else { std::cout<< "MultiSet is not empty" << std::endl; } return 0; }
Output
MultiSet is empty MultiSet is not empty
Summary
Today, we learned how to check if multiset is empty in C++?.