简体   繁体   English

关于 C++ 中 bool 数组的初始化

[英]Regarding initialization of bool array in C++

I was doing one programming problem, there I initialized the bool array like following:-我正在做一个编程问题,在那里我初始化了 bool 数组,如下所示:-

bool hash[n] = {0};

I submitted the code and I got the wrong answer.我提交了代码,但我得到了错误的答案。 I tried to figure out what is the problem.我试图找出问题所在。 Then I changed the above statement to following:-然后我将上述语句更改为以下内容:-

bool hash[n];
fill(hash, hash + n, 0);

This gave correct answer.这给出了正确的答案。 I didn't understand why the bool array initialization is not working.我不明白为什么布尔数组初始化不起作用。

After that just out of curiosity, I tried following:-之后出于好奇,我尝试了以下操作:-

bool hash[n] = {0};
fill(hash, hash + n, 0);

I submitted the code and I got wrong answer.我提交了代码,我得到了错误的答案。 This really blew my mind.这真的让我大吃一惊。 Any inputs?有输入吗?

I was able to reproduce this error by going through a few online c++ compilers.通过几个在线 c++ 编译器,我能够重现此错误。 (some of them accept VLAs following C99 and don't throw any errors) (其中一些接受 C99 之后的 VLA 并且不抛出任何错误)

Writing写作

int n=20;
bool hash[n]={0};

throws:抛出:

main.cpp:6:13: error: variable-sized object may not be initialized bool hash[n]={0}; main.cpp:6:13: 错误:可变大小的 object 可能未初始化 bool hash[n]={0}; ^ 1 error generated. ^ 1 个错误生成。 compiler exit status 1编译器退出状态 1

As extensively discussed in the comments above, declaring array size/length at runtime is not a feature of standard C++.正如上面评论中广泛讨论的那样,在运行时声明数组大小/长度不是标准 C++ 的功能。

However, this would work:但是,这会起作用:

int n=20;
bool hash[n];

because the array elements are not specified/initialized.因为未指定/初始化数组元素。

For reproducability, here is the link of the online compiler which produced this case.为了重现性,这里是产生这个案例的在线编译器的链接。

Always use vectors for such cases.对于这种情况,请始终使用向量。

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

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