Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a float array on construction

Tags:

c++

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

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?

like image 788
Aslan986 Avatar asked Oct 02 '12 16:10

Aslan986


People also ask

How do you initialize a float array?

Initializing a float Array in JavaArrays are declared with [] (square brackets). If you put [] (square brackets) after any variable of any type only that variable is of type array remaining variables in that declaration are not array variables those are normal variables of that type.

Can we store float in array in C?

Yes. Of course by occupying more than one int16_t element of the array (two, as float has size 4).

Are arrays automatically initialized C++?

Static arrays, and those declared directly in a namespace (outside any function), are always initialized. If no explicit initializer is specified, all the elements are default-initialized (with zeroes, for fundamental types).

Can size of array be float?

dataType: This is the data type that specifies the type of elements to be stored in the array. It can be int, float, double, char.


2 Answers

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:

std::vector<float> new_vec(dimension, 0);
like image 66
hmjd Avatar answered Oct 04 '22 18:10

hmjd


float* new_arr = new float[dimension]();
like image 23
none Avatar answered Oct 04 '22 17:10

none