I am learning about queues and am trying to write a method to change the maximum capacity of a circular queue using a dynamic array. This is what my code looks like right now.
void ArrayQueue::setCapacity(unsigned newCapacity){
if(newCapacity == 0 || newCapacity < this->getSize()){
throw QueueException("setCapacity()", "invalid new capacity");
} else if(newCapacity != this->getSize()){
Item * tempArray = new Item[newCapacity];
for(unsigned i=0; i<newCapacity; i++){
tempArray[i] = myArray[i];
}
Item * oldArray = myArray;
myArray = tempArray;
delete [] oldArray;
}
this->myCapacity = newCapacity;
}
However, when I decrease the capacity, I fail assertions to get the myFirst and myLast values. I understand that I need to write code to account for a case in which the entries have wrapped around but am confused about how to do so.
The test I'm trying to pass has code as follows:
ArrayQueue q5(10);
for (int i = 0; i < 10; i++){
q5.append(i+1);
}
for (int i = 0; i < 7; i++){
q5.remove();
}
assert( q5.getCapacity() == 10 );
assert( q5.getSize() == 3 );
assert( !q5.isEmpty() );
assert( !q5.isFull() );
assert( q5.getFirst() == 8 );
assert( q5.getLast() == 10 );
//reduce the capacity
q5.setCapacity(5);
assert( q5.getCapacity() == 5 );
assert( q5.getSize() == 3 );
assert( !q5.isEmpty() );
assert( !q5.isFull() );
assert( q5.getFirst() == 8 );
assert( q5.getLast() == 10 );
I'm passing my first set of assertions but the second getFirst assertion is failing.
Could you give me a pointer in the right direction? Thanks.
If your new capacity is larger, then you will access myArray with invalid indices