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:

The stack is :     1    5    20    30    10

s.size() : 5
s.top() : 1
s.pop() :     5    20    30    10

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

// CPP code to illustrat
// Queue in Standard Template Library (STL)
#include <iostream>
#include <queue>
  
using namespace std;
  
void showq(queue <int> gq)
{
    queue <int> g = gq;
    while (!g.empty())
    {
        cout << '\t' << g.front();
        g.pop();
    }
    cout << '\n';
}

int main()
{
    queue <int> gquiz;
    gquiz.push(10);
    gquiz.push(20);
    gquiz.push(30);
  
    cout << "The queue gquiz is : ";
    showq(gquiz);

    cout << "\ngquiz.size() : " << gquiz.size();
    cout << "\ngquiz.front() : " << gquiz.front();
    cout << "\ngquiz.back() : " << gquiz.back();

    cout << "\ngquiz.pop() : ";
    gquiz.pop();
    showq(gquiz);

    return 0;
}

Output:

The queue gquiz is :     10    20    30

gquiz.size() : 3
gquiz.front() : 10
gquiz.back() : 30
gquiz.pop() :     20    30

Last updated