将原始数组初始化为一个值
有没有办法将基元数组(例如整数数组)初始化为 0?不使用for循环?寻找不涉及 for 循环的简洁代码。
:)
Is there a way to initialize an array of primitives, say a integer array, to 0? Without using a for loop? Looking for concise code that doesn't involve a for loop.
:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请注意,如果您想要一种更通用的方法来结束:
要获得:
应该提到
std::fill
只是您试图避免的循环的包装器,并且= {};
可以用这样的术语来实现。Note if you want a more generic way to get the end:
To get:
It should be mentioned
std::fill
is just a wrapper around the loop you're trying to avoid, and= {};
might be implemented in such terms.是的,这是可能的。初始化方法取决于上下文。
如果您要声明静态或本地数组,请使用
= {}
初始值设定项如果您要使用
new[]
创建数组,请使用()
项如果要在构造函数初始值设定项列表中初始化非静态成员数组,请使用
()
初始值设定Yes, it is possible. The initialization method depends on the context.
If you are declaring a static or local array, use
= {}
initializerIf you are creating an array with
new[]
, use()
initializerIf you are initializing a non-static member array in the constructor initializer list, use
()
initializer如果您希望所有值都为零,可以使用 memset。另外,如果您只想初始化为零,则可以将数组声明为放置在内存的 ZI 部分。
You can use memset if you want all your values to be zero. Also, if you're only looking to initialize to zero, you can declare your array in such a way that it is placed in the ZI section of memory.
如果数字为零,您也可以使用 memset (尽管这更像是 C 风格):
If the number is zero you could also use memset (though this is more C-style):
双 A[10] = { 值 }; // 将 A 初始化为值。
我不记得值是否必须编译为常量。
不适用于自动数组
double A[10] = { value }; // initialize A to value
.I do not remember if value has to be compiled constant or not.
will not work with automatic arrays
有多种方法可以隐藏您使用不同语法所做的事情,这就是其他答案给您的 -
std::fill、memset、={}
等。但在一般情况下(不包括编译器特定的技巧(如 ZI 之一),考虑编译后的代码需要做什么:块/数组开始;
依次阻塞到该值;
已到达块的末尾。
换句话说,需要以相当基本的方式存在一个循环。
There are ways of concealing what you are doing with different syntax, and this is what the other answers give you -
std::fill, memset, ={}
etc. In the general case, though (excluding compiler-specific tricks like the ZI one), think about what needs to be done by the compiled code:block/array starts;
block to the value in turn;
the end of the block has been reached.
In other words, there needs to be a loop in a fairly fundamental way.