我想要初始化一个双重布尔类型的数组,并将其值设置为true。
bool a[5][5] = {{true}}; //这样是可行的
fill(a,a+sizeof(a),true); // This throws an error too.
如何完成这个?
我想要初始化一个双重布尔类型的数组,并将其值设置为true。
bool a[5][5] = {{true}}; //这样是可行的
fill(a,a+sizeof(a),true); // This throws an error too.
bool a[5][5] {{true, true, true, true, true},
{true, true, true, true, true},
{true, true, true, true, true},
{true, true, true, true, true},
{true, true, true, true, true}};
这是正确的,但是不太稳定——当您更改数组大小而没有更改true, true, true...
部分时,添加到数组中的部分将使用false
进行初始化。
最好使用for循环来完成此操作:
bool a[5][5];
for (auto& r: a)
for (bool& b: r)
b = true;
或者使用 std::vector
:
std::vector<std::vector<bool> > a(5, {true, true, true, true, true});
vector<bool>
很邪恶,因为它是一种特殊情况下的空间优化容器(位标志)。如果你仍想使用它,你可以使用std::vector<std::vector<bool>> a(5, std::vector<bool>(5, true));
进行初始化。 - dyp
std:fill(&a[0][0],&a[4][4]+1,true)
,但这是邪恶的,不是严格合法的C++,但通常可以工作,所以... - n. m.a[0]
的指针开始,最终越界了。 - n. m.