CodesJava

Easy learning with example program codes

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.

 

Syntax:

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:

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

 

CPP Stack Functions:

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

 

Example:

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

Output

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
Please follow and like us:
Posted in CPP   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki