gpt4 book ai didi

C++ 堆栈实现

转载 作者:搜寻专家 更新时间:2023-10-31 00:49:21 26 4
gpt4 key购买 nike

大家好!我的堆栈有点麻烦。我正在尝试打印已压入堆栈的每个元素。

从堆栈构造函数开始,我们知道数组的大小是固定的。所以我分配了项目结构对象来容纳那么多空间:

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;陈述。我一直在尝试找出如何在插入堆栈后将项目数组拖出 (+) 以查看所有数组元素。

我想知道为什么我不能在调试时将 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;
}

我走了很远,如果有人有时间,我需要一些指导!

最佳答案

在 for 循环中重载的 << 运算符中,您将迭代 maxsize 次。但是您可能没有将 maxsize 元素压入堆栈。你应该迭代最高时间。此外,为项目结构编写一个默认构造函数并初始化所有变量,这样当您尝试打印它们时就不会得到垃圾值。

关于C++ 堆栈实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1403517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com