Initializing Primitive Array to One Value
Is there a way to initialize an array of primitives,开发者_如何学C say a integer array, to 0? Without using a for loop? Looking for concise code that doesn't involve a for loop.
:)
int array[10] = {}; // to 0
std::fill(array, array + 10, x); // to x
Note if you want a more generic way to get the end:
template <typename T, size_t N>
T* endof(T (&pArray)[N])
{
return &pArray[0] + N;
}
To get:
std::fill(array, endof(array), x); // to x (no explicit size)
It should be mentioned std::fill
is just a wrapper around the loop you're trying to avoid, and = {};
might be implemented in such terms.
Yes, it is possible. The initialization method depends on the context.
If you are declaring a static or local array, use = {}
initializer
int a[100] = {}; // all zeros
If you are creating an array with new[]
, use ()
initializer
int *a = new int[100](); // all zeros
If you are initializing a non-static member array in the constructor initializer list, use ()
initializer
class C {
int a[100];
C() : a() // all zeros
{
...
}
};
You can use memset if you want all your values to be zero. Also, if you're only looking to initialize to zero, you can declare your array in such a way that it is placed in the ZI section of memory.
If the number is zero you could also use memset (though this is more C-style):
int a[100];
memset(a, 0, sizeof(a));
double A[10] = { value }; // initialize A to value
.
I do not remember if value has to be compiled constant or not.
will not work with automatic arrays
There are ways of concealing what you are doing with different syntax, and this is what the other answers give you - std::fill, memset, ={}
etc. In the general case, though (excluding compiler-specific tricks like the ZI one), think about what needs to be done by the compiled code:
- it needs to know where your memory block/array starts;
- it needs to set each element of the block to the value in turn;
- it needs to check repeatedly whether the end of the block has been reached.
In other words, there needs to be a loop in a fairly fundamental way.
精彩评论