C++如何将结构数组初始化为null,然后在while循环中检查该数组的元素是否为null

C++ How can I initialize array of structs to null and later check if an element of this array is null in a while loop?

本文关键字:null 数组 是否 循环 元素 检查 while 结构 初始化 然后 C++      更新时间:2023-10-16

我正试图用C++中的循环数组编写一个队列实现。我做对了这一部分,但我的任务要求我在main.cpp中的一个函数中打印队列。这给我带来了一个问题,因为我必须在while循环中打印它,并且队列的大小不一定是编译时的最大大小。

例如:如果用户在最大大小为3的队列中排队2名乘客,并且我想打印队列中的乘客,那么我必须让while循环只进行2次迭代。但我不允许传递队列的大小,所以我唯一能做到这一点的方法是检查队列中的乘客结构是否为NULL。我不知道NULL在structs的上下文中是什么意思。

这是我的头文件CQueue.h

const int MAX = 3;
struct Passenger {
char name[80];
};
class CQueue {
private:
int front;
int rear;
Passenger passengers[MAX];
public:
CQueue();
bool IsEmpty();
bool IsFull();
void Enqueue(Passenger);
Passenger Front(); // Returns the passenger type at the front index of array
void Dequeue();
};

这是我在CQue.cpp 中的类构造函数

CQueue::CQueue() // Custom constructor initializes the fields of the CQueue class with the appropriate values
{
front = -1; // Conditions for emptiness of CQueue
rear = -1; // Conditions for emptiness of CQueue
??? // needs a line to initialize passengers[MAX] elements to some default NULL value
}

这就是我在main.cpp中要做的。我试图按顺序打印Queue元素,但只打印用户输入的元素。换句话说,我不想打印空的元素。

while (???) // check if passanger is not the default null value
{
cout << CQueue.Front() << "n";
copyQueue.Dequeue();
}

我不确定该用什么来代替???。我尝试了很多不同的方法,但归根结底,我不知道结构的NULL值是什么

提前感谢!

乘客数组是一个对象数组,而不是指针数组,因此不能有"NULL"乘客。但是,与其把它们改为指针,一个更干净的设计是计算出CQueue中的乘客数量,并用它来检查乘客是否是"默认值"。类似于:

bool CQueue::IsEmpty() { return rear != -1 && front != -1; }
bool CQueue::IsFull() { return rear - front >= MAX; }

然后:

CQueue::CQueue() // Custom constructor initializes the fields of the CQueue class with the appropriate values
{
front = -1; // Conditions for emptiness of CQueue
rear = -1; // Conditions for emptiness of CQueue
}

和:

while (!copyQueue.IsEmpty())
{
cout << CQueue.Front() << "n";
copyQueue.Dequeue();
}