[英]C++ Stack Implementation
Hey all! 大家好! Having a little trouble with my stack. 我的堆栈有点麻烦。 Im trying to print each element that I've pushed onto the stack. 我正在尝试打印我推入堆栈的每个元素。
Starting with the stack ctor we know that we have a fixed size for the array. 从堆栈ctor开始,我们知道数组的大小是固定的。 So I allocate the items struct object to hold just that much space: 所以我分配了项目struct对象来容纳这么多的空间:
stack::stack(int capacity)
{
items = new item[capacity];
if ( items == NULL ) {
throw "Cannot Allocoate Sufficient Memmory";
exit(1);
}
maxSize = capacity;
top = -1;
}
Yes, items is a struct type of the object "item". 是的,items是对象“ item”的结构类型。 Have a look: 看一看:
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)
...
First and formost we want to add to the stack by pushing each incoming element into the array FILO: 首先也是最重要的一点是,我们希望通过将每个传入元素推入数组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;
}
Yes the real issue for me is the items[++top].n = n; 是的,对我来说真正的问题是项目[++ top]。n= n; statement. 声明。 I've been trying to find out how I can drag (+) the items array out to see ALL of the array elements after I push onto the stack. 我一直在尝试找出如何在推入堆栈后将项目数组拖出(+)以查看所有数组元素。
Im wondering why I cant drag that items[++top].n = n statement out when im debugging. 我想知道为什么在调试时不能拖动该项[++ top] .n = n语句。 All that comes up is the value that is passed as an 'n' paramater. 所有出现的就是作为“ n”参数传递的值。 Do I need to use a stack object type array to store the values into? 我是否需要使用堆栈对象类型数组将值存储到其中?
When I overload the << operator and try to print the elements I get an insanely large negative number: 当我重载<<操作符并尝试打印元素时,我得到一个非常大的负数:
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;
}
I'm way off and I need some guidence if anyone has the time! 我要走了,如果有时间,我需要一些指导!
In the overloaded << operator in the for loop you are iterating maxsize times. 在for循环的重载<<操作符中,您要迭代maxsize时间。 But you might not have pushed maxsize elements into the stack. 但是您可能尚未将maxsize元素推入堆栈。 You should iterate top times. 您应该遍历高峰时间。 Also, write a default constructor for item structure and initialize all the variblaes so that you do not get garbage values when you try to print them. 另外,为项结构编写一个默认的构造函数,并初始化所有变量,以便在尝试打印它们时不会得到垃圾值。
在打印纸叠时,您应该只向上放置,而不是最大尺寸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.