C++ Standard Library C++ STL Library

C++ <stack> - empty() Function



The C++ stack::empty function is used to check whether the stack is empty or not. It returns true if the size of the stack is zero, else returns false.

Syntax

bool empty() const;
bool empty() const;

Parameters

No parameter is required.

Return Value

true if the size of the stack is zero, else returns false.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the stack::empty function is used to check whether the stack is empty or not.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> MyStack;

  cout<<boolalpha;

  cout<<"Is the Stack empty?: "<<MyStack.empty()<<"\n";

  cout<<"Add elements in the Stack.\n";
  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);

  cout<<"Now, Is the Stack empty?: "<<MyStack.empty()<<"\n";
  return 0;
}

The output of the above code will be:

Is the Stack empty?: true
Add elements in the Stack.
Now, Is the Stack empty?: false

❮ C++ <stack> Library