Search code examples
c++arraysqueuecircular-buffer

C++ circular array queue setCapacity


I am working on an assignment that involves me writing a template class for a queue. It uses a dynamically allocated array. I am having trouble with the copying of the array. This is the prompt.

aQueue.setCapacity(newCapacity), that changes the capacity of aQueue to newCapacity. (This is much trickier than Stack::setCapacity(): if newCapacity is zero or < getSize(), setCapacity() should throw an exception; otherwise, it should allocate a new array with the new capacity, copy the values from the old array into the new array, and deallocate the old array.) To help you see all the things that can go wrong, you should make certain your method passes all the tests in this test method before working on the rest of the project.

Instance variables are:

unsigned mySize;       // number of items I contain
unsigned myCapacity;   // how many items I can store
unsigned myFirst;      // index of oldest item (if any)
unsigned myLast;       // index of next available spot for append (if any)
Item*    myArray;      // dynamic array of items

This is what I have so far:

template <class Item>
void ArrayQueue<Item>::setCapacity(unsigned newCapacity) {
    if (newCapacity == 0 || newCapacity < mySize) {
        throw QueueException("setCapacity()","newCapacity is too small");
    } else {
        Item * newArray = new Item[newCapacity];
        unsigned y = myFirst;
        for (unsigned x = 0; x < mySize; x++) {
            newArray[y] = myArray[x];
            y++;
        }
        delete [] myArray;
        myArray = newArray;
        myCapacity = newCapacity;
        myLast = y;
    }
}

These are the methods for getFirst() and getLast():

// Method returns first Item in ArrayQueue
template <class Item>
unsigned ArrayQueue<Item>::getFirst() const {
    if (this->isEmpty()) {
        throw EmptyQueueException("getFirst()");
    } else {
        return myArray[myFirst];
    }
}

// Method returns last Item in ArrayQueue
template <class Item>
unsigned ArrayQueue<Item>::getLast() const {
    if (this->isEmpty()) {
        throw EmptyQueueException("getLast()");
    } else {
        return myArray[(myLast - 1 + myCapacity) % myCapacity];
    }
}

I have been working on this for hours so any help would be greatly appreciated.


Solution

  • Credit goes to: Aconcagua

        for (unsigned x = 0; x < mySize; x++) {
            newArray[x] = myArray[(y % myCapacity)];
            y++;
        }
        delete [] myArray;
        myArray = newArray;
        myCapacity = newCapacity;
        myFirst = 0;
        myLast = mySize;
    

    By setting myFirst to 0 and myLast to mySize this properly allocates the indexes correctly. In addition to this when copying the array you most set newArray[x] to myArray[(y % myCapacity)].