[英]C++ initialize bool array
In C++ we'd use std::fill
:在 C++ 中,我们会使用
std::fill
:
bool* flags = new bool[n];
std::fill(flags, flags+n, false); // Also works with `true`.
The problem is that sizeof(flag)
has no idea about the size of the array allocated to the pointer flag
.问题是
sizeof(flag)
不知道分配给指针flag
的数组的大小。 The size of the pointer is fixed for the architecture, meaning that only the initial part of the dynamic array would be initialized (or cause undefined behavior if n
is small).指针的大小对于体系结构是固定的,这意味着只有动态数组的初始部分会被初始化(如果
n
很小,则会导致未定义的行为)。
If you insist on using "plain" array of bool
, change the initialization code to this:如果您坚持使用
bool
“普通”数组,请将初始化代码更改为:
memset(flags, false, sizeof(*flags)*n); // Wouldn't work with true
A better approach is to use std::vector<bool>
, which uses an implementation that saves you a lot of memory compared to a "plain" array of bool
:更好的方法是使用
std::vector<bool>
,它使用的实现与bool
的“普通”数组相比可以节省大量内存:
int countPrimes(int n) {
std::vector<bool> flag(n, false);
int res = 0;
for (int i = 0 ; i != n ; i++) {
...
}
return res;
}
Note that the use of std::vector<bool>
frees you from having to call delete[] flags
when you are done with the dynamically allocated array.请注意,当您完成动态分配的数组时,使用
std::vector<bool>
使您不必调用delete[] flags
。
A size of the array item is sizeof(bool)
or equivalent sizeof *flag
, the size of the array is n*sizeof(bool)
or n*sizeof *flag
, not sizeof flag
.数组项的大小是
sizeof(bool)
或等效的sizeof *flag
,数组的大小是n*sizeof(bool)
或n*sizeof *flag
,而不是sizeof flag
。 The value sizeof flag
is most likely 4 (a size of a pointer type), hence 4 items of your array got set to 0
( false
).值
sizeof flag
很可能是 4(指针类型的大小),因此数组的 4 个项目被设置为0
( false
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.