Is there a way to initialize an array of primitives, say a integer array, to 0? Without using a for loop? Looking for concise code that doesn't involve a for loop.
:)
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.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
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.
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