从堆栈开始,我们知道我们有一个固定的数组大小。所以我分配了项目struct对象来保存那么多空间:
stack::stack(int capacity)
{
items = new item[capacity];
if ( items == NULL ) {
throw "Cannot Allocoate Sufficient Memmory";
exit(1);
}
maxSize = capacity;
top = -1;
}
是的,items是对象“item”的结构类型。看看:
class stack
{
stack(int capacity);
~stack(void);
...
private:
int maxSize; // is for the item stack
int top; // is the top of the stack
struct item {
int n;
};
item *items;
public:
friend ostream& operator<<(ostream& out, stack& q)
...
首先,我们希望通过将每个传入元素推入数组FILO来添加到堆栈中:
bool stack::pushFront( const int n )
{
if ( top >= maxSize-1 )
{
throw "Stack Full On Push";
return false;
}
else
{
++top;
items[top].n = n;
}
return true;
}
// just a textbook example here:
stack::~stack(void)
{
delete [] items;
items = NULL;
maxSize = 0;
top = -1;
}
是的,对我来说真正的问题是项目[++ top] .n = n;声明。我一直试图找出如何在推入堆栈后将item数组拖出(+)以查看所有数组元素。
我想知道为什么我不能在调试时拖动那些项目[++ top] .n = n语句。所有出现的都是作为'n'参数传递的值。我是否需要使用堆栈对象类型数组将值存储到?
当我重载&lt;&lt;运算符并尝试打印元素我得到一个非常大的负数:
ostream& operator<<(ostream& out, stack& q)
{
if ( q.top <= 0 ) // bad check for empty or full node
out << endl << "stack: empty" << endl << endl;
else
for ( int x = 0; x < q.maxSize; x++ )
{
out << q.items[x].n; // try to print elements
}
return out;
}
我离开了,如果有人有空的话,我需要一些指导!
答案 0 :(得分:3)
在重载&lt;&lt; for循环中的运算符,您正在迭代maxsize次。但是你可能没有将maxsize元素推入堆栈。你应该迭代顶级时间。另外,为项结构编写一个默认构造函数并初始化所有的variblaes,这样当你尝试打印它们时就不会得到垃圾值。
答案 1 :(得分:2)
打印堆栈时,您应该只达到顶部,而不是达到maxSize。