Signup/Sign In

QUEUE Container in STL

The queue container is used to replicate queue in C++, insertion always takes place at the back of the queue and deletion is always performed at the front of the queue.

Here is the syntax for defining a queue:

queue< object_type >  queue_name;

The above statement will create a queue named queue_name of type object_type.


Member Functions of Queue Container

Following are some of the commonly used functions of Queue Container in STL:


push function

push() is used to insert the element in the queue. The element is inserted at the back or rear of the queue.

push method of queue

#include <iostream>      
#include <queue> 

using namespace std;   
     
int main ()
{
    queue <int> q;   // creates an empty queue of integer q 
    
    q.push>(2);   // pushes 2 in the queue  , now front = back = 2
    q.push(3);   // pushes 3 in the queue  , now front = 2 , and back = 3
}

pop function

This method removes single element from the front of the queue and therefore reduces its size by 1. The element removed is the element that was entered first. the pop() does not return anything.

pop method of queue

#include <iostream>      
#include <queue> 

using namespace std;   
     
int main ()
{
    queue <int> q;   // creates an empty queue of integer q 
    
    q.push>(2);   // pushes 2 in the queue  , now front = back = 2
    q.push(3);   // pushes 3 in the queue  , now front = 2 , and back = 3
    
    q.pop() ;  // removes 2 from the stack , front = 3
}

front and back functions

front() returns the front element of the queue whereas back() returns the element at the back of the queue. Note that both returns the element, not removes it, unlike pop().


size and empty functions

size() returns the number of elements present in the queue, whereas empty() checks if the queue is empty or not. empty returns true if the queue is empty else false is returned.


Swap function

Method swap() Swaps the elements of the two queue.