【发布时间】:2021-02-25 21:23:38
【问题描述】:
我正在使用数组实现 ADT 堆栈。当堆栈已满时,我想将数组的大小增加一倍。
const int MAX_SIZE = 6 // max size of array stack
template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
ItemType items[MAX_SIZE]; // Array of stack items
int top; // index of top
int itemCount; // Amount of items in stack
int maxsize;
这是我的推送方法:
template<class ItemType>
bool ArrayStack<ItemType>::push(const ItemType& newEntry){
if(itemCount == maxsize){ // resize array
cout << "resizing an array..." << endl; // just for testing
ItemType* oldArray = items; // old array to be deleted
ItemType* newItems = new ItemType[2*maxsize];
for(int i=0; i<maxsize; i++){
newItems[i] = oldArray[i]; // copying all array items
}
delete[] oldArray; // deallocate
maxsize = maxsize * 2; // doubling max size
items = newItems; <- I'm getting error from this code
} // end if
// Stack is not full
top++;
items[top] = newEntry;
itemCount++;
return true;
}
我在尝试将数组大小加倍时遇到此错误:
error: array type 'int [6]' is not assignable
items = newItems;
我该如何解决这个问题?
【问题讨论】:
-
您是否有理由手动管理动态数组而不是使用
std::vector?甚至,你为什么不使用std::stack开始? -
实际上我正在学习“数据抽象和用 C++ 解决问题”,我在第 7 章,他们创建了这样的数组堆栈类,并在“堆栈变满时将数组加倍”正如我在代码中指出的那样,他们确实将数组加倍
-
不能改变fixed数组的大小,只能分配一个新的dynamic数组并维护一个指针 给它。
-
@RemyLebeau 我绝对同意你的观点,这就是为什么我在这里问这个问题,因为当我在书中看到问题的答案时它没有意义
-
如果书籍显示一个指针被分配给一个数组,那么这本书是错误的。