c++数据结构的实现类

我想用c++写一个队列类,看到网上有结构体是这么写的

typedef struct Queue_tag{ int data[MAXSIZE]; 
    int front,rear;
}QUEUE;

但是实例化类时好像只能通过改写MAXSIZE来更改队列初始化大小
我想在构造函数里输入参数来确定大小,于是我写了下面的结构体,然后在函数里new了一个随参数改变长度的数组,并让*arr指向这个数组,请问这么做有没有问题,我看好多代码数组在结构体里都直接确定了大小,那有没有什么办法可以不通过更改宏定义而是通过构造函数来初始化大小呢

struct queue
{
    T *arr;
    T *head;
    T *tail;}*q;

    void initQueue(int lenght)
    {
        q = new queue;
        T *p = new T[lenght];
        q->arr = p;
        q->head = p;
        q->tail = p;
    }


人到中年有点甜
浏览 909回答 2
2回答

扬帆大鱼

我的想法是,既然是用C++去解决这个问题,那么就用C++的封装方式去解决。在C++中,一切皆对象,那么就定义一个类queue,具体的实现可以参考STL的queue实现。如果是想用C的方式去解决,那么就用链表方式struct _Node{char* data; struct _Node* priv; struct _Node* next;};data在程序执行时,创建有malloc完成,删除有free完成。我的理解是C和C++不是一样的语言。

德玛西亚99

template<T>class QUEUE{private:&nbsp; &nbsp; T* data;&nbsp; &nbsp; int front;&nbsp; &nbsp; int rear;&nbsp; &nbsp; int size;public:&nbsp; &nbsp; QUEUE() {}&nbsp; &nbsp; QUEUE(int sz)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; data = new T(sizeof(T) * sz);&nbsp; &nbsp; &nbsp; &nbsp; size = sz;&nbsp; &nbsp; &nbsp; &nbsp; /*your code below*/&nbsp; &nbsp; }&nbsp; &nbsp; ~QUEUE()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; delete data;&nbsp; &nbsp; &nbsp; &nbsp; data = nullptr;&nbsp; &nbsp; }};题主如果是练手,可以像上面这样,自己重载一个构造函数就行了。如果是为了项目要用,直接用std::queue。另外一般的FIFO队列,用链表实现更方便,而且易于增删元素。这种用数组实现的一般用于循环队列。
打开App,查看更多内容
随时随地看视频慕课网APP