Stack in C++ Standard Template Library (STL)

In this tutorial, we are going to learn about some special functions of stack in STL in C++. It is nothing but a special type of container adaptor which is specifically designed to operate in a LIFO context (last-in-first-out). We can insert and extract elements only from one end of the container.

Functions Associated with Stack in C++

The functions which are associated with stack are as follows:

  • push( a )
  • pop( )
  • top( )
  • empty( )
  • size( )

We will discuss each function one by one and then we will implement it in our code.




Push(a)

This function adds the element (a) in the top of the stack and the time complexity of this operation is O(1).

Pop()

This function removes the top element from the stack and the time complexity of this operation is O(1).

Top()

This function returns the element which is present in the top of the stack and the time complexity of this operation is O(1).

Empty()

This function checks if the stack is empty or not. The time complexity of this operation is O(1).

Size()

This function returns the size of the stack at a particular point of time. The time complexity of this operation is O(1).

Now we will try to implement each function in our code.

Code to implement the following stack functions in C++

Cpp source code:

// C++ program to implement stack STL 
#include<bits/stdc++.h> 
using namespace std; 

int main () 
{ 
  stack <int> s; 
  s.push(11); 
  s.push(12); 
  s.push(13); 
  s.push(14); 
  s.push(15); 
  // After inserting 5 elements we are checking the size of stack
  cout<<"Stack size: "<<s.size();
  
  // Checking out the top element present in stack
  cout<<"\nTop element present in stack is: "<<s.top();
  
  // Removing the top element from the stack
  s.pop();
  
  // Now printing all the elements of the stack
  // until it is empty.
  cout<<"\nElements present in the stack is: ";
  while(!s.empty())
  {
    cout<<s.top()<<" ";
    s.pop();
  }
  return 0; 
}

Input/Output: (Stack program in C++)

Stack size: 5
Top element present in stack is: 15
Elements present in the stack is: 14 13 12 11

You may also learn:

Merge sort in C++ (A Divide and Conquer algorithm)

Program on Quicksort on Linked List in C++

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.


Leave a Reply

Your email address will not be published. Required fields are marked *