Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the “back” of the specific container, which is known as the top of the stack.

Member Functions

  • bool empty() const;
    Returns whether the stack is empty: i.e. whether its size is zero.
  • void pop();
    Removes the element on top of the stack, effectively reducing its size by one.
  • void push (const value_type& val);
    void push (value_type&& val);
    Inserts a new element at the top of the stack, above its current top element. The content of this new element is initialized to a copy of val.
  • size_type size() const;
    Returns the number of elements in the stack.
  • void swap (stack& x) noexcept;
    Exchanges the contents of the container adaptor (*this) by those of x.
  • reference& top();
    const_reference& top() const;
    Returns a reference to the top element in the stack.



#include <iostream> 
#include <stack> 
using namespace std; 

int main () 
  stack <int> s; 
  int sum = 0;

  // Size of stack
  cout << s.size(); 
  // Top element of the stack
  cout <<; 

  // Removing top element
  // Traversing till the end of the stack
  while (!s.empty())
    sum +=;

  return 0;