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


    stack<T> st; //declaration
    int st.size();


    No parameter passed

Return type: int

Header file to be included:

    #include <iostream>
    #include <stack>
    #include <bits/stdc++.h>


The function returns the current size of the stack.

Time complexity: O(1)


    For a stack of integer,
    stack<int> st;
    stack content:
    5 <-- TOP

    int temp=st.size() //2
    Print temp//prints 2 which is current stack size

C++ implementation:

#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
    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
    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;   


...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

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.