I naively thought I could use memset for this, but apparently memset is only for chars. Is there a memset-type thing that will work on an array of floats? Or is simple iteration the fastest way to copy a single value to every spot in an array?
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
float array[4]; array[0] = 3.544; array[1] = 5.544; array[2] = 6.544; array[3] = 6.544; This should work buddy. Save this answer.
Yes. Of course by occupying more than one int16_t element of the array (two, as float has size 4).
You can call it like this: //fixed arrays int a[10]; setValue(a, 0); //dynamic arrays int *d = new int[length]; setValue(d, length, 0); Above is more C++11 way than using memset.
I won't speak to what code runs the fastest. You should compare them yourself, in the intended environment.
But, here are two readable, maintainable, correct solutions.
std::fill(std::begin(array), std::end(array), 3.14);
Or, if you have a dynamic array:
std::fill(array, array+size, 3.14);
The standard way is:
std::fill(float_array, float_array + array_size, 0.0f);
I suspect you could beat this standard facility without non-standard methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With