簡體   English   中英

C ++堆棧實現

[英]C++ Stack Implementation

大家好! 我的堆棧有點麻煩。 我正在嘗試打印我推入堆棧的每個元素。

從堆棧ctor開始,我們知道數組的大小是固定的。 所以我分配了項目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; 聲明。 我一直在嘗試找出如何在推入堆棧后將項目數組拖出(+)以查看所有數組元素。

我想知道為什么在調試時不能拖動該項[++ 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元素推入堆棧。 您應該遍歷高峰時間。 另外,為項結構編寫一個默認的構造函數,並初始化所有變量,以便在嘗試打印它們時不會得到垃圾值。

在打印紙疊時,您應該只向上放置,而不是最大尺寸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM