C ++ Stack by Array Implementation

时间:2009-09-07 03:41:46

标签: c++ struct

我想要发生的是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;
}

是的,我的主要问题是项目[++ top] = n;声明。我一直试图找到解决方法,如下所示:


bool stack::pushFront(const int n)
{
    int *a = new int[maxSize];
    a[++top] = n;

    return true;
}

但我不能拖出(+)'a'数组来查看那些实际的数组元素......这就是我希望发生的事情..

我想要的是语句项目[++ top] = n;工作..

3 个答案:

答案 0 :(得分:2)

您无法为项目分配int值,因为您尚未告诉编译器如何执行此操作。

您需要为将int作为参数或使用

的项编写构造函数或operator =
items[++top].n = n;

答案 1 :(得分:0)

看来你已经定义了一个固定大小的堆栈。您应该检查添加到堆栈的大小是否超过。要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;
}

答案 2 :(得分:0)

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
}