【发布时间】:2017-04-09 21:39:40
【问题描述】:
我正在处理一项涉及我为队列编写模板类的任务。它使用动态分配的数组。我在复制数组时遇到问题。这是提示。
aQueue.setCapacity(newCapacity),将aQueue的容量更改为newCapacity。 (这比 Stack::setCapacity() 复杂得多:如果 newCapacity 为零或
实例变量是:
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];
}
}
我已经为此工作了几个小时,因此我们将不胜感激。
【问题讨论】:
-
手动“执行”你的复制代码。这将引导您解决主要问题。除此之外:1)
myMember成员的名称不是惯用的 C++。 2)您正在手动管理动态内存,不要忘记 3/5 规则。 3)您不应该手动管理动态内存,尝试使用例如std::vector作为你的后备记忆。 -
我想使用一个向量,但是对于这个任务,我需要使用一个数组...
-
在 for 循环中使用 y % newCapacity 作为 newAarray 的索引怎么样?
-
这有帮助,谢谢。但是,在我的测试方法中,myFirst 和 myLast 的断言仍然失败。我不确定如何正确设置这些变量。这是我的测试方法:
-
//在一个队列上测试 setCapacity(),该队列的项目开始//在数组的中间,而不是环绕 ArrayQueue
q4(5); for (int i = 0; i
标签: c++ arrays queue circular-buffer