[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

free store new double[]

Hicham Mouline

11/21/2008 2:55:00 PM

hi,

Is there a way to allocate an array and initialize in the same statement?

double* d = new double[n];
and assign immediately a value, say NaN

what i'm doing now is just:

for (size_t i=0; i<n; ++i)
d[i] = NaN;

regards,


3 Answers

Pete Becker

11/21/2008 3:00:00 PM

0

On 2008-11-21 09:55:18 -0500, "Hicham Mouline" <hicham@mouline.org> said:

>
> Is there a way to allocate an array and initialize in the same statement?

Sure. Use a vector.

>
> double* d = new double[n];
> and assign immediately a value, say NaN
>
> what i'm doing now is just:
>
> for (size_t i=0; i<n; ++i)
> d[i] = NaN;
>

vector<double> vec(n, NaN);

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Maxim Yegorushkin

11/21/2008 3:17:00 PM

0

On Nov 21, 2:55 pm, "Hicham Mouline" <hic...@mouline.org> wrote:

> Is there a way to allocate an array and initialize in the same statement?

As Pete already said, std::vector<double> d(n, NaN) is the easiest and
most recommended.

> double* d = new double[n];
> and assign immediately a value, say NaN
>
> what i'm doing now is just:
>
> for (size_t i=0; i<n; ++i)
>   d[i] = NaN;
>

Another way:

double* d = std::fill_n(new double[n], n, NaN) - n;

Or (save a subtraction):

double* d;
std::fill_n((d = new double[n]), n, NaN);

--
Max

Andrey Tarasevich

11/21/2008 3:40:00 PM

0

Hicham Mouline wrote:
> hi,
>
> Is there a way to allocate an array and initialize in the same statement?
>
> double* d = new double[n];
> and assign immediately a value, say NaN

If you were looking for zeroes, the you could just do

double* d = new double[n]();

> what i'm doing now is just:
>
> for (size_t i=0; i<n; ++i)
> d[i] = NaN;

Otherwise, to meet your "one statement" requirement, the only thing you
can do is replace you explicit cycle with a standard (or your own)
function with equivalent functionality.

--
Best regards,
Andrey Tarasevich