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.

 

Example

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

int main () 
{ 
  stack <int> s; 
  int sum = 0;
  
  s.push(10); 
  s.push(30); 
  s.push(20); 
  s.push(5); 
  s.push(1); 

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

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

  return 0; 
}