I am reading about FIFO queue array implementeation in Algorithms in C++ by Robert Sedwick.. The contents of the queue are all the elements in the array between “head” and “tail”, taking into account the wraparound back to 0 when the end of the array is encountered. If “head” and “tail” are equal, then we consider the queue to be empty; but if “put” would make then equal, then we consider it to be full. We are making the size of the array 1 greater than the maximum number of elements that the client expects to see in the queue so that we could augument this program to make error checks.
template <class Item>
class QUEUE
{
private:
Item *q; int N, head, tail;
public:
QUEUE(int maxN)
{ q = new Item[maxN+1];
N = maxN+1; head = N; tail = 0; }
int empty() const
{ return head % N == tail; }
void put(Item item)
{ q[tail++] = item; tail = tail % N; }
Item get()
{ head = head % N; return q[head++]; }
};
My question why author as mentioned in text allocating array 1 greater than user specified for making error checks. I am not getting how allocating 1 greater than user request will help us in error checking? Please help me with sample code.
Thanks for your time and help.
I think that, without the extra cell, there would be no way to distinguish between a queue with maxN elements and an empty queue, since head and tail would be in the same equivalence class modulo maxN in both cases.
So, I guess error handling could be done right after a put, to check that the empty criterion is not fulfilled (which means capacity was exceeded):
and likewise at the beginning of get, to check that the queue is not empty.
Does it make sense?