In our previous post, we looked at the modelling of the Queue class using an array as the container to hold the queue elements. front and rear indicate the boundary of the queue (the first and the last elements). When we want to add a new element, we add it at the rear. Likewise, when we want to remove and process an element, we remove it from the front. That is, enqueue increments the rear member and dequeue increments the front member.


Queue Operations

void Queue::enqueue (int item) {
  if (rear >= MAXSIZE - 1)
    throw out_of_range("Queue is full. Nothing can be enqueued now.");
  else {
    arr[++rear] = item;
  }
}

int Queue::dequeue () {
  if (rear == -1)
    throw out_of_range("Can not dequeue from empty queue");
  return arr[front++];
}

So, when front = rear there is only one element and if front > rear, the queue is empty (recollect that the front is initialized to 0 and rear is initialized to -1).

bool Queue::is_empty () {
  return (front > rear);
}

Although pretty straight-forward, Queues have a variety of applications. We will soon see some applications when we discuss Graph data structures.