【问题标题】:C++ Stack by Array Implementation数组实现的 C++ 堆栈
【发布时间】:2010-11-26 03:00:54
【问题描述】:

我想要的是 pushFront(int) 函数这样做:

布尔堆栈::pushFront( const int n ) { 项目[++顶部] = n; // 其中top是栈顶 返回真; // 只有推送成功才返回true }

items 是对象“item”的结构类型。看看:

类堆栈 { 堆栈(整数容量); 〜堆栈(无效); ... 私人的: 诠释最大尺寸; // 用于项目堆栈 诠释顶部; // 是栈顶 结构项目{ 诠释n; }; 项目*项目;

我已将 ctor 定义为堆栈类对象和 dtor,如下所示:

堆栈::堆栈(整数容量) { 项目=新项目[容量]; 如果(项目== NULL){ 抛出“无法分配足够的内存”; 退出(1); } 最大尺寸 = 容量; 顶部 = -1; } 堆栈::~堆栈(无效) { 删除 [] 项; 项目=空; 最大尺寸 = 0; 顶部 = -1; }

是的,对我来说主要问题是 items[++top] = n;陈述。我一直在尝试寻找解决方法,如下所示:

布尔堆栈::pushFront(const int n) { int *a = new int[maxSize]; 一个[++顶部] = n; 返回真; }

但我无法将 (+) 'a' 数组拖出以查看那些实际的数组元素......这正是我希望发生的......

我想要的是语句 items[++top] = n;上班。。

【问题讨论】:

    标签: c++ struct


    【解决方案1】:

    您不能将 int 值分配给项目,因为您还没有告诉编译器如何执行此操作。

    您需要为将 int 作为参数的项目编写构造函数或 operator= 或使用

    items[++top].n = n;
    

    【讨论】:

      【解决方案2】:
      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
      }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 其实语句 items[++top] = n;在 bool stack::pushFront(const int n) 函数的主体内,无效,我收到此错误:错误 C2679:二进制“=”:未找到采用“const int”类型的右侧操作数的运算符(或没有可接受的转换)。后跟:可能是 'stack::item &stack::item::operator =(const stack::item &)' 我怎样才能摆脱将代码编写为 items[++top] = n; ?
        • 在我使用项目作为分配给 n 的数组的任何地方,我都会收到一个错误:/
        • 正如 Geerad 指出的那样:items[++top].n = n;因为 items 是一个结构。
        猜你喜欢
        • 2010-12-15
        • 1970-01-01
        • 2010-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多