mintbox
mintbox

Reputation: 167

Initializing array of fundamental types

When creating an array of fundamental type such as :

double *aPtr = new double[10];

Is there a way of initializing it to a specific value? ((ex)-1)

Is creating a new class the only way?

Upvotes: 3

Views: 139

Answers (5)

Stefan Ivanov
Stefan Ivanov

Reputation: 41

You can initialize fundamental types to be zero using uniform initialization.

double *aPtr = new double[10] {}

This will zero out the created array. You can also do this in C++03 using "()" instead of "{}".

However, this does not initialize all of the elements to a specific value. If you write new double[10] {-1.0} you will get an array with the first element being -1.0 and the other nine - 0.0.

You can specify all of the elements using an initializer list like this, but it is not scalable for large arrays. Instead, I believe that using std::fill_n or std::fill after the call to new is a better and simpler solution.

If you really want to not have a loop (even inside an algorithm) you can use variadic templates to generate an initializer list but that will require some work to get it to work correctly.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

For such small arrays you can write explicitly

double *aPtr = new double[10] 
{ 
    ex -1, ex -1, ex -1, ex -1, ex -1, ex -1, ex -1, ex -1, ex -1, ex -1 
};

However for a larger array you should use some standard algorithm as for example std::generate, std::generate_n, std::fill, std::fill_n, std::for_each or even some kind of loop.

For example

std::generate( aPtr, aPtr + 10, [value = ex - 1]{ return value; } );

or

std::generate_n( aPtr, 10, [value = ex - 1]{ return value; } );

or

std::fill( aPtr, aPtr + 10, ex - 1 );

or

std::fill_n( aPtr, 10, ex - 1 );

or

std::for_each( aPtr, aPtr + 10, [value = ex - 1]( auto &x ){ x = value; } );

If the compiler does not support the init capture you can write for example

std::generate( aPtr, aPtr + 10, [=]{ return ex - 1; } );

Upvotes: 0

Izuka
Izuka

Reputation: 2612

The fill_n function can be what you are looking for. It will assign the n first values of your array with a specific value.

double *aPtr = new double[10];

std::fill_n(aPtr, 10, -1); // Fill the aPtr array with the value -1 for the 10 first values.

I do not know a specific way to fill it directly with one same value at declaration.

Upvotes: 3

fatihk
fatihk

Reputation: 7919

you can use std::fill_n:

std::fill_n(aPtr , 10, -1);

Upvotes: 2

Alireza Jafari
Alireza Jafari

Reputation: 32

if u want to initialize array of double and set values to 0 u can use:

double* aPtr = (double*)calloc(10,sizeof(double));

if u want set value of elements after decleration u can use:

double *aPtr = new double[10]; memset(aPtr,value,size);

same question and ur answer in detail:

using memset in double type array

Upvotes: -1

Related Questions