【发布时间】:2025-12-06 20:35:01
【问题描述】:
我正在尝试实现“堆栈”类的一些方法。对于 push() 方法,如果堆栈顶部等于容量,我试图复制数组的容量。顶部是下一个插槽的项目。我通过创建一个容量是原始数组两倍的新数组然后复制内容来做到这一点。我实现的所有其他方法(empty()、pop()、top())似乎工作正常,但是如果堆栈有超过 10 个元素,push 函数会出于某种原因打印堆栈的前 4 个项目的随机值(必须增加容量)。为什么会出现这个问题?
#include <iostream>
using namespace std;
class stack
{
public:
stack();
bool empty();
void pop();
void push(int x);
int &topElem();
private:
int *buffer;
int top; // Top element of stack
int capacity = 10; // Capacity of array
};
stack::stack()
{
int *val = new int[capacity];
buffer = val;
top = 0;
}
bool stack::empty()
{
if(top == 0)
return true;
else
return false;
}
void stack::push(int x)
{
if(top == capacity)
{
int *newArray = new int[capacity * 2];
for(int i = 0; i < capacity; i++)
{
newArray[i] = buffer[i];
//cout << "newArray[" << i << "]: " << newArray[i] << endl;
}
buffer = newArray;
delete[] newArray;
newArray = NULL;
}
buffer[top] = x;
top++;
}
void stack::pop()
{
if(!empty())
{
top--;
}
else
cout << "Stack is empty!" << endl;
}
int& stack::topElem()
{
return buffer[top - 1];
}
int main()
{
stack plates;
for (int i = 0; i < 20; i++) // Add 20 elements to the stack
{
plates.push(i);
}
while (!plates.empty())
{
cout << plates.topElem() << endl; // Prints the elemtents of the stack
plates.pop(); // Pops the last element of the stack
}
return 0;
}
// 输出 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 393 -1250224288 393 -1250206816
【问题讨论】:
-
Delete NewArray 是错误的 - 你想在那里缓冲,并在分配 NewArray 之前将其删除。