Open In App

How to Find the Size of a Stack in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the stack is a container that follows the Last In First Out (LIFO) rule. While working with a stack, the size of the stack is required in various operations. In this article, we will learn how to find the size of a stack in C++.

Example:

Input:
myStack = {40, 30, 20, 10} 
Output:
Size of the stack is : 4

Finding the Size of a Stack in C++

To find the size of a std::stack in C++, we can use the std::stack::size() function provided by the std::stack class template that returns an integer value that denotes the stack container’s number of elements.

C++ Program to Find the Size of a Stack

The below example demonstrates how we can use the std::size() function to find the size of a stack in C++.

C++




// C++ Program to illustrate how to find the size of the
// stack
#include <iostream>
#include <stack>
using namespace std;
  
int main()
{
    // Creating a stack
    stack<int> myStack;
  
    // Pushing elements into  the stack
    myStack.push(10);
    myStack.push(20);
    myStack.push(30);
    myStack.push(40);
  
    // Finding the size of the stack using size() function
    cout << "Size of the stack is: " << myStack.size()
         << endl;
    return 0;
}


Output

Size of the stack is: 4

Time Complexity: O(1)
Auxiliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads