A queue is a linear data structure that serves as a container of objects that are inserted and removed according to the FIFO (First–In, First–Out) principle.

 
Queue has three main operations: enqueue, dequeue, and peek. We have already covered these operations and C implementation of queue data structure using an array and linked list. In this post, we will cover queue implementation in C++ using class and STL.

 
The following queue implementation in C++ covers the following operations:

  • Enqueue: Inserts a new element at the rear of the queue.
  • Dequeue: Removes the front element of the queue and returns it.
  • Peek: Returns the front element present in the queue without dequeuing it.
  • IsEmpty: Checks if the queue is empty.
  • IsFull: Checks if the queue is full.
  • Size: Returns the total number of elements present in the queue.

Practice this problem

Queue Implementation using an array:

Download  Run Code


Output:
 
Inserting 1
Inserting 2
Inserting 3
The front element is 1
Removing 1
Inserting 4
The queue size is 3
Removing 2
Removing 3
Removing 4
The queue is empty

 
The time complexity of all the above queue operations is O(1).

Using std::queue:

C++’s STL provides a std::queue template class which is restricted to only enqueue/dequeue operations. It also provides std::list which has push_back and pop_front operations with LIFO semantics. Java’s library contains Queue interface that specifies queue operations.

std::queue


Download  Run Code

std::list


Download  Run Code

Output:
 
The queue size is 4
The front element is A
The rear element is D
The queue size is 2
The queue is not empty

 
Also See:

Queue Implementation in Java

Queue Implementation in Python