How to Find the Size of a Stack in C++?
Last Updated :
05 Mar, 2024
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++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.push(40);
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)
Share your thoughts in the comments
Please Login to comment...