【问题标题】:C++ Stack ImplementationC++ 堆栈实现
【发布时间】: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]。我点击它,但我只得到作为参数传递的值。你知道链表吗?你可以在哪里拖出所有这些节点..这就是我的意思哈哈,很抱歉造成混乱,感谢您的帮助!
  • 我们都假设您已经定义了复制构造函数和赋值运算符。否则代码使用起来很危险。

标签: c++ struct stack


【解决方案1】:

在 for 循环中重载的

【讨论】:

  • 假设您将堆栈的容量声明为 10 并推送 4 个元素。在您的 for 循环中,您将迭代 10 次。前 4 个将打印正确的值,但接下来的 6 个将是垃圾,因为您既没有初始化也没有为结构项中的变量 n 分配任何值。所以如果你为item结构写了一个默认的构造函数,当你在stack的构造函数中new item[capacity]时会调用它,并且n会被正确初始化。
【解决方案2】:

在打印堆栈时,您应该只上到顶部,而不是上到 maxSize。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2020-09-13
    • 2011-12-04
    相关资源
    最近更新 更多