The std::stack class is a container adapter that gives the programmer the functionality of a stack - specifically, a FILO (first-in, last-out) data structure.
The class template acts as a wrapper to the underlying container - only a specific set of functions is provided. The stack pushes and pops the element from the back of the underlying container, known as the top of the stack.
A small demo program of stack
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack <int> s; //declaring a stack variable which will hold integer values
for (int i = 0; i < 10; i++) {
s.push(i); //pushing element inside the stack
}
while (!s.empty()) {
cout << "Element at the top : ";
cout << s.top();
cout << " size of stack ";
cout << s.size() << endl;
s.pop(); //remove the last element from the stack
}
return 0;
}
Output of the above program will be :
Element at the top : 9 size of stack 10
Element at the top : 8 size of stack 9
Element at the top : 7 size of stack 8
Element at the top : 6 size of stack 7
Element at the top : 5 size of stack 6
Element at the top : 4 size of stack 5
Element at the top : 3 size of stack 4
Element at the top : 2 size of stack 3
Element at the top : 1 size of stack 2
Element at the top : 0 size of stack 1
Member functions of Stack are given below
Element access
top
Capacity
empty
size
Modifiers
push
pop
emplace
swap
Some applications of Stack
- Expression Evolution
- Expression conversion
- Infix to Postfix
- Infix to Prefix
- Postfix to Infix
- Prefix to Infix
- Parsing
- Simulation of recursion
- Fuction call
0 Comment(s)