Nov 13, 2018

Stack in C++ STL

Stack / Queue in C++ STL

Stack

The functions associated with stack are:

empty() – Returns whether the stack is empty – Time Complexity : O(1) size() – Returns the size of the stack – Time Complexity : O(1) top() – Returns a reference to the top most element of the stack – Time Complexity : O(1) push(g) – Adds the element g at the top of the stack – Time Complexity : O(1) pop() – Deletes the top most element of the stack – Time Complexity : O(1)

// CPP program to demonstrate working of STL stack 
#include <iostream> 
#include <stack> 
using namespace std; 
  
void showstack(stack <int> s) 
{ 
    while (!s.empty()) 
    { 
        cout << '\t' << s.top(); 
        s.pop(); 
    } 
    cout << '\n'; 
} 
  
int main () 
{ 
    stack <int> s; 
    s.push(10); 
    s.push(30); 
    s.push(20); 
    s.push(5); 
    s.push(1); 
  
    cout << "The stack is : "; 
    showstack(s); 
  
    cout << "\ns.size() : " << s.size(); 
    cout << "\ns.top() : " << s.top(); 
  
  
    cout << "\ns.pop() : "; 
    s.pop(); 
    showstack(s); 
  
    return 0; 
}

Output:

Queue

Queues are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front.

The functions supported by queue are :

  1. empty() – Returns whether the queue is empty

  2. size() – Returns the size of the queue

  3. front() – Returns a reference to the first element of the queue

  4. back() – Returns a reference to the last element of the queue

  5. push(g) – Adds the element g at the end of the queue

  6. pop() – Deletes the first element of the queue

Output:

Last updated