Error al verificar la implementación de la cola en C++
Frecuentes
Visto 357 veces
1
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.
Gracias por tu tiempo y ayuda.
2 Respuestas
3
Because if the array had the same size as the maximum number of elements inserting the last element would cause tail
ser igual a head
, and you would not be able to distinguish an empty queue from a full one by just comparing head
y tail
.
Respondido 24 ago 12, 10:08
0
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):
void put(Item item)
{
q[tail++] = item;
tail = tail % N;
// check that capacity is not exceeded.
if (head % N == tail)
throw;
}
and likewise at the beginning of get, to check that the queue is not empty.
¿Tiene sentido?
Respondido 24 ago 12, 11:08
can you please add some example code in above code to show me how this is done. Thankis - venkysmarty
Assume you would like a capacity of maxN = 2 and you allocated N = 2 as well, then when if you insert two elements, you will have tail = 0 and head = 0 again (tail = tail % N at the end of put) and empty() will return true although it is not. - ghislain fourny
Gracias por una explicación detallada. - venkysmarty
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c++ algorithm or haz tu propia pregunta.
I am looking for how allocating 1 greater helps in error checking? - venkysmarty