# Built in queue in C++

  • Queue is a linear data structure which follows FIFO i.e. First-In-First-Out method.

  • The two ends of a queue are called Front and Rear, where Insertion always takes place at the Rear and the elements are accessed or removed from the Front.

  • To use queue we have to include header file #include <queue>and then we can define a queue of any type using the general format queue <TYPE> name; for example:

    1. queue <int> q1; will create an integer queue called q1
    2. queue <char> q2; will create a character queue called q2
    3. queue <float> q3; will create a float number queue called q3
  • Suppose we create a queue q1 of type integer : queue <int> q1;

  • Enqueue : to perfrom enqueue operation we have the function void push(value) which takes the value to be inserted as argument, example :

    1. q1.push(1); will push the value 1 in the queue q1.
    2. q1.push(2); will push the value 2 in the queue q1.
    3. q1.push(4); will push the value 4 in the queue q1.
  • Show element at front and rear : The front() function which returns a reference to the element at front and The back() function which returns a reference to the element at rear. example :

    1. cout<< q1.front()<<" "<< q1.back(); will produce the output : 1 4
  • Dequeue : We will use the void pop() function to remove values from queue. For example :

    1. q1.pop(); will remove the element 1 from the queue.
  • To check if queue is empty or not : We will use the bool empty() function to check if the queue is empty or not which will return 1 if the queue is empty, otherwise it will return 0.

  • Size : We will use the size() function which returns the number of elements in the queue. For example :

    1. cout<< q1.size(); For this queue the output will be 3.

# Source Code - C++

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

void displayQueue(queue<int> q)
{
 int n = q.size();

 for(int i=0; i<n;i++)
 {

  cout<<q.front()<<" ";
  q.pop();
 }
 cout<<"\n";

}

int main(){

 queue<int> q1;

 //Enqueue - Pushing elements to queue
 q1.push(1);
 q1.push(2);
 q1.push(4);

 cout<<"Elements of Queue are : ";
 //display Queue
 displayQueue(q1);

 //Show front and rear of queue
 cout<<"Element at front is : "<<q1.front()<<"\n";
 cout<<"Element at rear is : "<<q1.back()<<"\n";

 //Dequeue - removing element from queue
 q1.pop();

 cout<<"Queue after pop operation : ";
 displayQueue(q1);

 //To check if queue is empty or not
 cout<<"Queue is empty or not : "<<q1.empty()<<"\n";

 //size of the queue
 cout<<"Size of the Queue is : "<<q1.size();

 return 0;

}