[Cs3] CS3 - Initializer list with new array

Mikhail Nesterenko mikhail at cs.kent.edu
Fri Jun 20 15:39:54 EDT 2014


> Can an new array somehow have an initializer list applied to it in the
> allocation statement?
> 
> Something like:
> 
> int *ary = nullptr;
> int size = 1;
> ary = new int[size] /* ...then the initializer list */;
> 
> instead of having to assign to that element?
> 
> ary = new int[size];
> ary[size - 1] = 5;
> 
> Specifically for when other class objects are being used used like in the
> WordList and WordOccurrence (lab 2) assignment.

No, initializer lists are not allowed for dynamic arrays. The idea is
that dynamic array is for an unknown number of elements. If the
elements are already known (so that they can be used in the
initializer list), then the array might as well by static. 

The closest c++ has is:

int *a = new int[length](); // invoking default constructor on each element of the array

Also, there is an STL function "fill" that we have not studied yet:

int *a = new int[length];
std::fill(a, a+length, 55 // assigns 55, array name is used as an iterator

With vectors, initialization is more straightforward:

std::vector<int>  v(length, 55);

Thanks,
--
Mikhail


More information about the cs3 mailing list