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循环中打印它,并且队列的大小不一定是编译时的最大大小。
例如:如果用户在最大大小为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();
}
相关文章:
- c++使用foreach使数组为null
- 如果我在相应 char 数组的声明中为其提供额外的元素,是否会自动设置 NULL?
- 如何在 C++ 中使用 NULL(或 0)初始化静态字符数组
- 正在将对象指针数组初始化为NULL
- 为什么具有单独字符的字符数组不像字符串文字那样以 null 终止符结尾?
- STD :: Sort将数组指针设置为NULL
- 我正在尝试计算 char 数组中的内容,直到 null 终止,但每次编译时,我都会得到一个比我的数组大的数字
- 如何在默认构造函数中将 char 数组初始化为 null
- 2D 数组内存分配 (malloc) 返回 NULL
- Node-ffi 绑定到 NULL 终止的 C 字符串数组,但得到“分段错误:11”
- C++如何将结构数组初始化为null,然后在while循环中检查该数组的元素是否为null
- 初始化数组中的每个变量以'0'与将它们全部初始化为 null 相同吗?
- 尝试用C 中的空地址(而非null)删除数组指针
- C :将文本文件的内容存储在2D数组中,作为字符串(用于NULL终结器的麻烦?)
- 在std::字符串或字符数组中间包含NULL字符的UPDATE
- 将数组中的元素设置为 0 或 NULL
- 正在初始化指向null的专用指针数组
- 将对象的数组设置为c 中的null
- 在此初始值设定项方法上将整个数组设置为 NULL 是否C++标准?
- Opencv:cvGetMat中的Null指针(传递Null数组指针)