What is stack.empty() in C++?

The stack.empty() function in C++ returns a true value (1) if the stack is empty. Otherwise, it returns false (0). In short, this function is used to check if the stack is empty.

The following illustration shows a visual representation of the stack.empty() function.

A visual representation of the stack.empty() function

In order to use the stack.empty() function, we must include stack in the program, as shown below:

#include <stack>

Syntax

stack_name.empty()
// where the stack_name is the name of the stack

Parameters

This function does not require any parameters.

Return value

If the queue is empty, the stack.empty() function returns a true value (1). Otherwise, it returns false (0).

Code

#include <iostream>
//header file
#include <stack>
using namespace std;
int main() {
//filled stack
stack<int> stack1;
stack1.push(0);
stack1.push(2);
stack1.push(5);
stack1.push(3);
stack1.push(1);
//stack1 = 1->3->5->2->0
cout<<"stack1 is empty: \n"<<stack1.empty()<<"\n";
//empty stack
stack<int> stack2;
cout<<"stack2 is empty: \n"<<stack2.empty();
}

Free Resources