gpt4 book ai didi

通过数组实现的 C++ 堆栈

转载 作者:行者123 更新时间:2023-11-28 03:59:50 25 4
gpt4 key购买 nike

我想要的是让 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;

关于通过数组实现的 C++ 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1387460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com