如何在阵列中存储多个队列?

How to store multiple queue in array?

本文关键字:队列 存储 阵列      更新时间:2023-10-16

我有一个队列类,我在其中实现队列结构。

#include "queue.h"
Queue::Queue()
{

}
Queue::Queue(int size){
front = rear = -1;
this->size = size;
Q = new int[size];
}
void Queue::enqueue(int x){
if (rear == size -1 ){
cout << " its full" << endl;
}else{
rear ++;
Q[rear] = x;
}
}
int Queue::dequeue(){
int x= -1;
if (rear == front){
cout << " its empty"<<endl;
}else{
front ++;
x = Q[front];
}
return x;
}
void Queue::Display(){
for(int i= front+1; i<=rear; i++){
cout << Q[i] << "  ";
}
cout << endl;
}
bool Queue::isEmpty(){
return (size==0);
}
int Queue::peek()
{
if (isEmpty())
{
cout << "UnderFlownProgram Terminatedn";
exit(EXIT_FAILURE);
}
return Q[front];
}

在 main.cpp 中,我创建了多个队列。我正在尝试实现一种调度算法,我需要按顺序处理每个队列。当我尝试遍历每个队列时,问题就开始了。我只想使用一个 for 循环来访问每个队列的元素,而不是每个队列的 for 循环。

例:

queue[1..N]其中N是队列数。在 for 循环中,我想检查if queue[i].empty().

我找到了解决问题的方法。总的来说.cpp,以下代码解决了这个问题。

Queue allQueues[4];
allQueues[0] = queue1;
allQueues[1] = queue2;
allQueues[2] = queue3;
allQueues[3] = queue4;

要访问:

for(int i=0; i<4; i++){
if allQueues[i].empty(){
//do something
}
}

如果需要生成特定数量的 Queue 类实例,这些实例在编译时是固定的和已知的,则代码解决方案将起作用。但是,如果您有一个程序,需要在程序运行时创建新的队列实例,则需要在堆上使用动态内存分配。

一种方法是在 main.cpp 中创建一个数组或指向 Queue 类的指针向量。 std::vector 更灵活,最好使用智能指针来创建队列的每个实例,尽管许多学术课程不允许使用标准模板库或智能指针,在这种情况下,您只需要一个指向 Queue 的普通指针数组,并适当地使用 new 和 delete。

const int SIZE = 100  //max number of Queue instances
Queue* allQueues[SIZE]; //array of uninitialized pointers to Queue
for (int i = 0; i < SIZE; i++) {  //ensure all pointers are set to null
allQueues[i] = nullptr;
}
//To make a new Queue instance and insert it into the array:
allQueues[0] = new Queue();
//And when done with that Queue instance, to avoid memory leaks and dangling pointers:
delete allQueues[0];
allQueues[0] = nullptr;

(使用std::array或std::vector和智能指针可以更好地完成(。 另请注意内存使用情况,如果没有此方法,您将有两个 queue1 队列的完整实例,而不是对象本身和指向该对象的指针。但是,也可以仅使用自动堆栈分配来执行指针数组操作,但是在这种情况下,您不希望在运行时创建新对象。为此,很简单:

Queue* allQueues[4];
allQueues[0] = &queue1;
//etc.

附言解决方案的一个问题是,当您执行此分配时:

allQueues[0] = queue1;

您需要类中的复制构造函数或重载的"="运算符,以确保 queue1 的所有内部结构都正确复制到 Queue 对象的数组中,并避免所有"浅拷贝"问题。

Queue::Queue(const Queue& copySource) {
this->size = copysource.size;
this->Q = new int[copysource.size];
for (int i = 0; i < size; i++) {
this->Q[i] = copysource.Q[i];
}

看: 为什么可以访问复制构造函数中的私有变量?