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 TYPE | USES |
container_type | To specify underlying container type. |
size_type | To specify the size range of the elements. |
value_type | To specify the element type. |
CPP Stack Functions:
FUNCTION | USES |
(constructor) | To construct a stack container. |
empty | To test for the emptiness of a stack and to get a true value if the stack is empty. |
emplace | To insert a new element in the stack above the current top element. |
push | To insert a new element at the top of the stack. |
pop | To delete the element in the stack from the top. |
swap | To interchange the contents of two containers in reference. |
size | To return the size of the stack container, which is a measure of the number of elements stored in the stack. |
top | To 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 |