【发布时间】:2014-03-09 14:11:40
【问题描述】:
我已经使用下一个类实现了一个堆栈:
template <typename T, int lungime> class Depou
{
private:
T *depouarray;
int top;
public:
Depou ()
{
this -> top = -1;
depouarray = (T *) calloc (lungime, sizeof (T));
}
~Depou ()
{
free (depouarray);
}
void push (T x)
{
if (top >= lungime - 1)
{
return;
}
top ++;
depouarray [top] = x;
}
T pop ()
{
if (isEmpty ())
{
return -1;
}
T x;
x = depouarray [top];
top --;
return x;
}
T peek ()
{
if (isEmpty ())
{
return -1;
}
return depouarray[top];
}
int isEmpty ()
{
return (top < 0);
}
}
我的问题是下一个: 在我将一个元素添加到堆栈后,比如说 3,我验证它并显示 3。 接下来,我添加了另一个元素,比如说 4,我验证了堆栈的内容,它显示了一个非常高的数字(这肯定是垃圾)和 4。我不明白为什么它将第一个元素转换为垃圾,只留下最后一个按原样添加元素。
【问题讨论】:
-
这是 C++。为什么要手动分配内存?
-
std::stack不适合你? -
为什么在 C++ 中使用
calloc和free? -
我要实现自己的栈,容量有限,必须动态分配。
-
我刚试了你的课,在推了 3 和 4 之后没有在堆栈中得到任何垃圾。请提供更多详细信息。