我想用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;
}
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.
No problem, as long as you can handle exceptions correctly and remember to release memory...
Why not
std::queue
...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
{
};
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.