Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Primitive Array to One Value

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.

:)

like image 288
bobber205 Avatar asked Apr 12 '10 21:04

bobber205


People also ask

How do you initialize an array with a single 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 initialize a primitive array in Java?

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.

What is the correct way of initialising an array?

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.


1 Answers

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.

like image 182
GManNickG Avatar answered Oct 20 '22 21:10

GManNickG