C++ 在构造时初始化一个浮点数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12694214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:32:36  来源:igfitidea点击:

Initialize a float array on construction

c++

提问by Aslan986

Is there a way in C++ to construct a float array initializing it's values?

在 C++ 中有没有办法构造一个浮点数组来初始化它的值?

For example, i do:

例如,我这样做:

float* new_arr = new float[dimension];
for(unsigned int i = 0; i < dimension; ++i) new_arr[i] = 0;

Is it possible to do the assignment during the contruction?

是否可以在施工期间进行分配?

回答by none

float* new_arr = new float[dimension]();

回答by hmjd

In this particular case (all zeroes) you can use value initialization:

在这种特殊情况下(全为零),您可以使用值初始化:

float* new_arr = new float[dimension]();

Instead of explicitly using new[]you could use a std::vector<float>instead:

new[]您可以使用 astd::vector<float>代替显式使用:

std::vector<float> new_vec(dimension, 0);