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

The stack.size() function in C++ returns the number of elements in the stack. In other words, this function is used to get the current size of the stack.

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

A visual representation of the stack.size() function

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

#include <stack>

Syntax

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

Parameters

This function does not require a parameter.

Return value

The stack.size() function returns the number of elements in the stack.

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<<"The length of stack1: \n"<<stack1.size()<<"\n";
//empty stack
stack<int> stack2;
cout<<"The length of stack2: \n"<<stack2.size();
}

Free Resources