Home »
C++ STL
stack::size() function in C++ STL
C++ STL stack::size() function with example: In this article, we are going to see how to find size of a stack using C++ STL?
Submitted by Radib Kar, on February 03, 2019
C++ STL - stack::size() function
The function returns the current size of the stack.
Syntax
stack<T> st; //declaration
int st.size();
Parameter(s)
This function does not accept any parameter.
Return value
This function returns the size of stack of "int" type.
Header file
Header file to be included:
#include <iostream>
#include <stack>
OR
#include <bits/stdc++.h>
Sample Input and Output
For a stack of integer,
stack<int> st;
st.push(4);
st.push(5);
stack content:
5 <-- TOP
4
int temp=st.size() //2
Print temp//prints 2 which is current stack size
Example
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<<"...use of size function...\n";
int count=0;
stack<int> st; //declare the stack
st.push(4); //pushed 4
st.push(5); //pushed 5
st.push(6);
cout<<"stack size is: "<<st.size()<<endl; //size function
cout<<"stack elements are:\n";
while(!st.empty()){//stack not empty
cout<<"top element is:"<<st.top()<<endl;//print top element
st.pop();
count++;
}
if(st.empty())
cout<<"stack empty\n";
cout<<"stack size is: "<<st.size()<<endl; //size function
cout<<count<<" pop operation performed total to make stack empty\n";
return 0;
}
Output
...use of size function...
stack size is: 3
stack elements are:
top element is:6
top element is:5
top element is:4
stack empty
stack size is: 0
3 pop operation performed total to make stack empty