C++ Standard Library C++ STL Library

C++ <stack> - size() Function



The C++ stack::size function is used find out the total number of elements in the stack.

Syntax

size_type size() const;
size_type size() const;

Parameters

No parameter is required.

Return Value

Number of elements present in the stack.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the stack::size function is used find out the total number of elements in a stack called MyStack.

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

  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);
  MyStack.push(40);
  MyStack.push(50);

  cout<<"Stack size is: "<<MyStack.size()<<"\n";

  cout<<"Three elements are added in the Stack.\n";
  MyStack.push(60);
  MyStack.push(70);
  MyStack.push(80);

  cout<<"Now, Stack size is: "<<MyStack.size()<<"\n";
  return 0;
}

The output of the above code will be:

Stack size is: 5
Three elements are added in the Stack.
Now, Stack size is: 8

❮ C++ <stack> Library