繁体   English   中英

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?

我正在尝试使用C ++中的循环数组编写队列实现。 我说的没错,但是我的作业要求我在main.cpp中的函数中打印队列。 这对我来说是一个问题,因为我将不得不在while循环中打印它,并且队列的大小不一定是编译时的最大大小。

例如:如果用户将2位乘客排队,最大队列大小为3,并且我想打印该队列中的乘客,则必须让while循环仅进行2次迭代。 但是我不允许传递队列的大小,所以我唯一可以做的就是检查队列中的乘客结构是否不是NULL。 我不知道NULL在结构上下文中是什么意思。

这是我的头文件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();
};

这是我在CQueue.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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM