CPP Stacks

Stack is a data structure in CPP that works on LIFO (Last In First Out) technique, which means that the last inserted element will be deleted first in a stack.



template<class T, class Container = deque<T> > class stack;


  • T:

It is used to represent the type of the element that the container adapter will store.

  • Container:

It is used to represent the internal object of the container where the stack elements are stored.


Member Types of CPP Stack:

container_typeTo specify underlying container type.
size_typeTo specify the size range of the elements.
value_typeTo specify the element type.


CPP Stack Functions:

(constructor)To construct a stack container.
emptyTo test for the emptiness of a stack and to get a true value if the stack is empty.
emplaceTo insert a new element in the stack above the current top element.
pushTo insert a new element at the top of the stack.
popTo delete the element in the stack from the top.
swapTo interchange the contents of two containers in reference.
sizeTo return the size of the stack container, which is a measure of the number of elements stored in the stack.
topTo access the top element of the stack.



#include <iostream>  
#include <stack>  
using namespace std;  
void display(stack <int> ds)  
stack <int> dis = ds;  
while (!dis.empty())  
	cout << dis.top() << " ";  
int main()  
stack <int> getstack;  
cout << "The stack element from top to bottom are  : ";  
cout << "\nThe value of getstack.size() : " << getstack.size();  
cout << "\nThe value of getstack.top() : " << getstack.top();  
cout << "\nThe value of getstack.pop() : ";  
return 0;  


The stack element from top to bottom are  : 30 50 60 80    
The value of getstack.size() : 4                
The value of getstack.top() : 30                                 
The value of getstack.pop() : 50 60 80
Content Protection by DMCA.com
Please Share