简体   繁体   English

在 C++ 中初始化一个数组:最快的方法?

[英]Initializing an Array in C++ : the fastest way?

What is the fastest way to initialize with zeros an array of int in C++?在 C++ 中用零初始化 int 数组的最快方法是什么?

int plus_number[CA - 1];
for (int & i : plus_number) {
    i = 0;
}

or或者

int plus_number[CA - 1] = {0};

or maybe there is another way?或者也许还有另一种方式?

Fastest way to initialise an array is to default initialise it.初始化数组的最快方法是默认初始化它。 In case of trivially default initialisable element type (and non-static storage duration), this leaves the elements with an indeterminate value.在默认初始化元素类型(和非静态存储持续时间)的情况下,这会使元素具有不确定的值。

You can use value initialisation instead if you want all elements to be zero.如果您希望所有元素都为零,则可以使用值初始化。 This may be marginally slower than default initialisation.这可能比默认初始化稍慢。 Both of your suggestions are potentially as fast as value initialisation.您的两个建议都可能与值初始化一样快。

You can simply use int plus_number[CA - 1]{};您可以简单地使用int plus_number[CA - 1]{};

This will zero-initialize all members of the array.这将对数组的所有成员进行零初始化。

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

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