Stack program using C++ Standard Template Library (STL)

C++ STL - Stack implementation: In this C++ program, we will learn about 'stack' which is a container type data type in C++ Standard Template Library (STL). Here we are implementing program with push(), pop() etc functions of 'stack'.
Submitted by IncludeHelp, on January 15, 2018

Stack are the linear data type in Data Structure, which follows LIFO (Last In First Out) approach (property), where insertion and deletion done by only one end, which is 'TOP'.

In C++ Standard Template Library (STL), Stack is a kind of container adapter declared in 'stack' header file. It has some built-in functions which are used to perform stack operations.

The stack functions in C++ STL

  1. stack() - It is used to check whether stack container is empty or not.
  2. size() - It returns the size (total number of elements in the stack) of the stack container.
  3. top() - It returns the next elements (top elements of the stack).
  4. push() - It inserts (pushes) the element into the stack.
  5. pop() - It removes the elements from the stack.

Reference: http://www.cplusplus.com/reference/stack/stack/

Program to implement stack using C++ STL

#include <iostream>
#include <stack>

using namespace std;

//function to dispay stack
void dispStack(stack <int> st){
    //declare temp. statck
    stack <int> s = st;
    while(!s.empty()){
        cout<<s.top()<<" ";
        s.pop();
    }
    cout<<endl;
}

//Main function for stack program
int main()
{
   //declare stack variable
   stack <int> st;
   
   //insert elements
   st.push(10);
   st.push(20);
   st.push(30);
   st.push(40);
   st.push(50);
   
   //display stack coun, top element and stack elements
   cout<<"Total stack elements are: "<<st.size()<<endl;
   cout<<"Top elements is: "<<st.top()<<endl;
   cout<<"All stack elements are: "<<endl;
   dispStack(st);
   
   //removing two stack elements
   st.pop();
   st.pop();
   
   cout<<"\nAfter removing two elements...\n";
    
    //AGAIN....
   //display stack coun, top element and stack elements
   cout<<"Total stack elements are: "<<st.size()<<endl;
   cout<<"Top elements is: "<<st.top()<<endl;
   cout<<"All stack elements are: "<<endl;
   dispStack(st);   
   
   return 0;
}

Output

Total stack elements are: 5
Top elements is: 50
All stack elements are: 
50 40 30 20 10 

After removing two elements...
Total stack elements are: 3
Top elements is: 30
All stack elements are: 
30 20 10 



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.