C++循环数组队列setCapacity

C++ circular array queue setCapacity

我正在完成一项作业,其中涉及为队列编写模板 class。它使用动态分配的数组。我在复制数组时遇到问题。这是提示。

aQueue.setCapacity(newCapacity),将aQueue的容量更改为newCapacity。 (这比 Stack::setCapacity() 更棘手:如果 newCapacity 为零或 < getSize(),setCapacity() 应该抛出异常;否则,它应该分配一个具有新容量的新数组,从

实例变量是:

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

这是我目前拥有的:

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;
    }
}

这些是 getFirst() 和 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];
    }
}

我已经为此工作了几个小时,因此非常感谢任何帮助。

致谢:阿空加瓜

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

通过将 myFirst 设置为 0 并将 myLast 设置为 mySize,这可以正确分配索引。除此之外,在复制数组时,您最常将 newArray[x] 设置为 myArray[(y % myCapacity)].