Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
mintbox Avatar asked Jun 19 '26 07:06

mintbox


2 Answers

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.

like image 187
Izukani Avatar answered Jun 20 '26 22:06

Izukani


you can use std::fill_n:

std::fill_n(aPtr , 10, -1);
like image 37
fatihk Avatar answered Jun 20 '26 22:06

fatihk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!