Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- fastest way to set an array of floats to the same value

Tags:

c++

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?

like image 864
morgancodes Avatar asked Nov 18 '11 19:11

morgancodes


People also ask

How do you initialize an entire array with the same value?

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.

How do you take a float array?

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.

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).

How do you reset all elements of an array to 0 in C++?

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.


2 Answers

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);
like image 178
Robᵩ Avatar answered Sep 18 '22 17:09

Robᵩ


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.

like image 41
Khaled Alshaya Avatar answered Sep 18 '22 17:09

Khaled Alshaya