Queue C++

Queue is a type of container adapter specially designed to work in first in first out context. In queue the element is inserted at the back-end and removed from front-end. For working on FIFO context queues are mainly used.

Basic Functions

Following are basic functions used with Queue:

Function Description
empty() Returns true if queue is empty
size() Returns the size of queue
push(g) Inserts element at the end of queue
pop() Removes element from the front of queue
queue::swap() in C++ STL
queue::swap() in C++ STL It will exchange contents of queue only if queue type is same. If there is difference in size then its ok
queue::front() in C++ STL Returns reference of first element in queue
queue::back() in C++ STL Returns reference of last element in queue


Following is an example for C++ queue:

// CPP code for illustration of Queue in Standard Template Library (STL)

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

void showQueue(queue <int> tq)
    queue <int> t = tq;
    cout << '\n';
    while (!t.empty()){
        cout << t.front() << ' ';
    cout << '\n';

int main(){
    queue <int> qfirst;


    cout << "Display queue qfirst : ";

    cout << "\nQueue Size qfirst.size() : " << qfirst.size();
    cout << "\nElement at front qfirst.front() : " << qfirst.front();
    cout << "\nElement at back qfirst.back() : " << qfirst.back();

    cout << "\n\nDisplaying queue before pop() operation : ";

    cout << "\nqfirst.pop() \n";

    cout << "\nDisplaying queue after pop() operation : ";

    return 0;

The output should be:

Display queue qfirst :
5 10 15 20 25

Queue Size qfirst.size() : 5
Element at front qfirst.front() : 5
Element at back qfirst.back() : 25Displaying queue before pop() operation :
5 10 15 20 25


Displaying queue after pop() operation :
10 15 20 25