Sunday, 5 March 2017

C++ Program for Implementing Stack Operations in STL

 The stack container is used to replicate stacks in c++, insertion and deletion is always performed at the top of the stack.

 To be able to use STL stacks in a file of C++ source code include <stack> (C++ Standard Library header File)

Suppose that T is any type or class - say an int, float, struct, or a class, then declaration will be stack<T> s; 

You can use following inbuilt methods to perform stack operactions in STL stack:

1.   s.empty() ;     // To check if stack is empty or not
2.   s.push(x);       //To insert element x in the stack
3.   s. top();          //To access top element of the stack
4.   s.size();          //To know the size of stack
5.   s.pop();          //To perform pop Operation in the stack

C++ Program for demonstrating the STL stack is given below.


PROGRAM:

#include <stdio.h>
#include <stack>
using namespace std;

class stackops
{
   private:
     std::stack<int> s;
   public:
     void top_element();
     void stack_size();
     void push_element();
     void pop_element();
     void stack_empty();
};
void stackops::top_element()
{
 int element=s.top();
 printf("\nThe top element of stack is: %d",element);
}
void stackops::stack_size()
{
 int size_of_stack=s.size();
 printf("\nThe size of stack is: %d",size_of_stack);
}
void stackops::push_element()
{
 int item;
 printf("\nEnter the element you want to insert in the stack: ");
 scanf("%d",&item);
 s.push(item);
}
void stackops::pop_element()
{
 s.pop();
 printf("\n\npop operations is performed, Updating stack\n");
}
void stackops::stack_empty()
{
   if(s.empty())
   {
       printf("\nStack is empty");
   }
   else
   {
       printf("\nStack is not empty");
   }
}
int main()
{
   stackops s1;
   s1.stack_empty();
   s1.push_element();
   s1.push_element();
   s1.push_element();
   s1.stack_size();
   s1.top_element();
   s1.pop_element();
   s1.top_element();
   s1.stack_empty();
   s1.stack_size();
      return 0;

}


OUTPUT:



EmoticonEmoticon