Pregunta

What is the fastest way to initialise, lets say, an integer array to a given value?

If I have char array, I can use memset:

char a[N];
memset( a, value, N );

I can't do memset if the array type != char and value != 0 or -1:

int a[N];
memset( a, value, N*sizeof(int) ); // INCORRECT!

So I wonder whether there is a way to do similar memory initialization for other array types.

¿Fue útil?

Solución

Use std::fill:

char a[N];
std::fill(std::begin(a), std::end(a), value);

Note that std::begin and std::end are defined as of C++11.

If you're using C++03, then this would work:

char a[N];
std::fill(a, a + N, value);

Otros consejos

There cannot be any way faster than aggregate initialization:

int x = {1,2,3,4,5,6};

If you want to initialize everything to zero, then you can leverage the syntax to value-initialize the entire array:

int x [50] = {};

This is different than:

int x[50];

Because when you specify an initializer, the uninitialized elements are value-initialized. If you don't specify an initializer, then the elements are uninitialized.

Just because there cannot be a faster method than int x[] = {....}, it's not necessarily true that other methods are slower. You need to profile in release mode on your actual platform to know for sure.

I suppose you can use memset with any primitive types.

int a[N] 
memset(a, '0x00', N * sizeof (int))

You can memset any kind of object/primitive. Everything is stored in memory after all.

That said you do have to understand how your compiler and processor store the thing you're memset'ing to predict what you will get. It's very non portable and dangerous if done wrong.

A lot of performance on modern desktop processors depends on if the objects you are referencing are in cache or not. So it's difficult to say if it will be faster. It's likely to be faster all other things being equal.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top