Home  >  Q&A  >  body text

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;
    }
怪我咯怪我咯2714 days ago582

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 13:37:43

    template<T>
    class QUEUE
    {
    private:
        T* data;
        int front;
        int rear;
        int size;
    public:
        QUEUE() {}
        QUEUE(int sz)
        {
            data = new T(sizeof(T) * sz);
            size = sz;
            /*your code below*/
        }
        ~QUEUE()
        {
            delete data;
            data = nullptr;
        }
    };

    If the questioner is practicing, you can just overload a constructor yourself as above. If it is used for a project, use std::queue directly. In addition, for general FIFO queues, it is more convenient to use a linked list, and it is easy to add and delete elements. This implementation using arrays is generally used for circular queues.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:37:43

    No problem, as long as you can handle exceptions correctly and remember to release memory...
    Why not std::queue...

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:37:43

    My idea is that since C++ is used to solve this problem, then C++ encapsulation should be used to solve it. In C++, everything is an object, so define a class queue. For specific implementation, please refer to STL's queue implementation.

    If you want to use C to solve the problem, then use the linked list method
    struct _Node
    {

    char* data;
    struct _Node* priv;
    struct _Node* next;

    };

    When the program is executed, the creation of data is completed by malloc, and the deletion is completed by free.
    My understanding is that C and C++ are not the same languages.

    reply
    0
  • Cancelreply