• Stack is an abstract data structure that contains a collection of elements.
  • It implements the Last In First Out (LIFO) mechanism this element is pushed at the end is popped out first.
  • It uses an encapsulated object of either deque or vector or list as its underlying container, providing a specific set of member functions to access its elements.
  • Stack class is a container adapter and container objects hold data of a similar data type.
  • From various sequence containers we can create a stack.
  • By default, deque container will be used, if there is no container is provided.
  • It cannot be used to manipulate, because container adapters don’t support iterators.
  • In stack Type is the Type of element contained and it can be any valid C++ type or even a user-defined type.
  • In stack containeris the Type of underlying container object.
  • Here three types of member types, they are:
    • Value_type- The first template parameter and donates the element types.
    • Container_type- The second template parameter and denotes the underlying container type.
    • Size_type- It is an unsigned integral type.

Syntax

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

Sample Code

#include <iostream>  
#include <stack>
using namespace std;
void newstack(stack <int> ss)
{
stack <int> sg = ss;
while (!sg.empty())
{
cout << '\t' << sg.top();
sg.pop();
}
cout << '\n';
}
int main ()
{
stack <int> newst;
newst.push(55);
newst.push(44);
newst.push(33);
newst.push(22);
newst.push(11);

cout << "The stack newst is : ";
newstack(newst);
cout << "\n newst.size() : " << newst.size();
cout << "\n newst.top() : " << newst.top();
cout << "\n newst.pop() : ";
newst.pop();
newstack(newst);
return 0;
}

Output

Categorized in: