> C++ Check if a Queue is FULL?

C++ Check if a Queue is FULL?

Posted at: 2014-12-18 
You didn't seem to have problems with writing an empty() method to test for an empty queue. So, write one.

bool full()

{

return (current size) >= (maximum size);

}

Then use:

if (full())

{

.... do something

}

What you do in braces there depends on the class specification. What is your function *supposed* to do when the queue is full? Twp common sensible things to do are to return a boolean value saying whether the enqueue succeeded, or to throw an exception. The all-too-common and evil thing to do is to return without saying or doing anything. Another evil thing to do is to print a message and abort. Other objects will not get destructor calls and may leave external resources in an invalid state. During debugging that might be acceptable, though.

re Update: You can only increment or decrement a pointer into an array, so you have an array somewhere. Besides, that's the only common queue data structure that "fills up". You allocated the array. It's not hard to count entries in the queue (set to zero on construction, add one on enqueue, subtract one on dequeue) so compare that with the allocated array size. The full() function is shown above.

That's assuming you use a "circular buffer" strategy, where "incrementing" a pointer to the last array entry resets back to the beginning of the array. That allows you to reuse the front of the array after items have been removed, without moving the whole queue forward. The "circular" description is based on the image of bending the array into a circle so that the first element comes immediately "after" the last one.

void enqueue(int val){

if (Queue is full, do this){

// What should I write here?

}else{

if(empty()){

r = f = 0;

}else{

r++;

int arr_length = (sizeof(arr)/sizeof(arr[0])) - 1;

if(r == arr_length)

r = 0;

}

arr[r] = val;

}

}

Please provide steps and explanation to this question. Thanks for your help!