C++ Unordered_set::empty() Function



TheC++std::unordered_set::empty() function is used to return a boolean value indicating whether the unordered_set container is empty or not.

If the unordered_set is empty, then begin() is equal to end(), and the empty() function returns true; otherwise, it returns false.

Syntax

Following is the syntax for std::unordered_set::empty.

bool empty() const noexcept;

Parameters

This function does not accepts any parameter.

Return Value

This function returns true if the container size is 0, otherwise false.

Example 1

Consider the following example, where we are going to demonstrate the usage of unordered_set::empty() function.

#include 
#include 
#include 

int main () {
   std::unordered_set first = {"sairam","krishna","mammahe"};
   std::unordered_set second;
   std::cout << "first " << (first.empty() ? "is empty" : "is not empty" ) << std::endl;
   std::cout << "second " << (second.empty() ? "is empty" : "is not empty" ) << std::endl;
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

first is not empty
second is empty

Example 2

Let's look at the following example, where we are going to use the empty() function to check whether the unordered_set is empty or not.

#include 
#include 
#include 
using namespace std;

int main () {
   unordered_set uSet;
   if(uSet.empty()==1){
      cout<

Output

If we run the above code it will generate the following output −

Is unordered_set empty? true

Example 3

In the following example, we are going to use the empty() function to check whether the unordered_set is empty or not and going to display the content of the unordered_set if it contains elements.

#include 
#include 
#include 
using namespace std;

int main () {
   unordered_set uSet{10, 20, 30, 40, 50};
   if(uSet.empty()==1){
      cout<

Output

Following is the output of the above code −

unordered_set contains following elements: 
50
40
30
20
10

Example 4

Following is the another example of the usage of the empty() function and displaying the result in the boolean value.

#include 
#include 
#include 
using namespace std;

int main () {
   unordered_set uSet;
   
   cout<

Output

Output of the above code is as follows −

boolean value before the insertion of elements: 
Is unordered_set empty? true
boolean value after the insertion of elements: 
Is unordered_set empty? false
Advertisements