[英]C++ Stack by Array Implementation
我想發生的是pushFront(int)函數執行此操作:
bool stack::pushFront( const int n ) { items[++top] = n; // where top is the top of the stack return true; // only return true when the push is successful }
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;
我已經將ctor定義為堆棧類對象和dtor,如下所示:
stack::stack(int capacity) { items = new item[capacity]; if ( items == NULL ) { throw "Cannot Allocoate Sufficient Memmory"; exit(1); } maxSize = capacity; top = -1; } stack::~stack(void) { delete [] items; items = NULL; maxSize = 0; top = -1; }
是的,對我來說,主要問題是items [++ top] = n; 聲明。 我一直在嘗試尋找解決方法,如下所示:
bool stack::pushFront(const int n) { int *a = new int[maxSize]; a[++top] = n; return true; }
但是我無法拖動(+)'a'數組來查看那些實際的數組元素...這就是我希望發生的事情。
我想要的是語句items [++ top] = n; 上班..
您不能將int值分配給項目,因為您尚未告訴編譯器該怎么做。
您需要為將int作為參數的項目編寫構造函數或operator =,或者使用
items[++top].n = n;
看來您已經定義了固定大小的堆棧。 您應檢查添加到堆棧中的大小不超過該大小。 要使用pushFront,您只需要復制數組中的數據即可為要修改的第0個元素騰出空間:
bool stack::push(const int n)
{
if ( top >= capacity-1 ) return false;
items[++top].n = n
}
bool stack::pushFront(const int n)
{
if ( top >= capacity-1 ) return false;
bcopy( items, items+1, top+1 );
items[0].n = n;
return true;
}
bool stack::pushFront( const int n )
{
if(top == maxSize-1)
return false;
items[++top].n = n; // where top is the top of the stack
return true; // only return true when the push is successful
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.