使用布尔值在c++中设置2d数组的值

Use boolean to set value of 2d array in C++

本文关键字:2d 数组 设置 布尔值 c++      更新时间:2023-10-16

我正在做航空公司预订项目,我的项目要求当一个座位被占用时它显示*,当它是空的时它显示#。我想将数组设置为布尔值,因此如果它为假,则为#,如果为真,则为*。这能行吗,还是说我错了?有更简单的方法吗?

bool seatFirst[4][3];
if(seatFirst == true)
    cout << "*" << endl;
else
    cout << "#";

这不起作用,因为您正在测试数组本身,它的值将为true。您需要测试单个元素。也不需要检查booltrue,您可以只执行if (theBool). Finally, you cannot append endl ; to a string literal, you need to "stream" it with an operator<<'。

在这里,使用三元操作符是为了使代码更简洁:

std::cout << (seatFirst[i][j] ? "*" : "#") << std::endl;