【发布时间】:2010-11-27 01:45:45
【问题描述】:
大家好!我的堆栈有点麻烦。我试图打印我推入堆栈的每个元素。
从堆栈 ctor 开始,我们知道数组的大小是固定的。所以我分配 items 结构对象来容纳这么多空间:
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;
}
是的,对我来说真正的问题是 items[++top].n = n;陈述。我一直在尝试找出如何在推入堆栈后将项目数组拖出 (+) 以查看所有数组元素。
我想知道为什么我不能在调试时拖出 items[++top].n = n 语句。出现的只是作为“n”参数传递的值。我需要使用堆栈对象类型数组来存储值吗?
当我重载
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;
}
我已经走了,如果有人有时间,我需要一些指导!
【问题讨论】:
-
您想在调试器中查看项目吗?您使用的是哪个编辑器?
-
不要在SO上使用pre标签,而是使用代码缩进按钮;查看我的最后一次编辑。
-
“拖出”是什么操作?
-
当我在 Visual Studio 中调试时,它们是那个自动变量项旁边的一个小加号[++top]。我点击它,但我只得到作为参数传递的值。你知道链表吗?你可以在哪里拖出所有这些节点..这就是我的意思哈哈,很抱歉造成混乱,感谢您的帮助!
-
我们都假设您已经定义了复制构造函数和赋值运算符。否则代码使用起来很危险。