Passing parameter when creating object array

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Aug 7 00:50:33 PDT 2007


James Dennett wrote:
> Daniel White wrote:
>> I've just found out from elsewhere that it's not possible in C++ to create an array of objects whilst simultaneously passing a parameter to the constructor of each of those objects. Something like this returns an error:
>>
>> Myclass x (10)[50]
>>
>> I don't want to have to do:
>>
>> Myclass x[5] = {10,10,10,10,10,10.................}  // ...and so on
>>
>> Does D support the more intuitive Myclass x (10)[50] mechanism?
> 
> C++ has a library type for arrays, where you can write
> 
> std::vector<MyClass> x(50, MyClass(10));
> 
> D tends to prefer pushing this kind of thing out of the library
> and into the language, but maybe somebody can point out the D
> library solution for this.
> 
> -- James

Its straightforward:

T[] populateArray (T) (int len, lazy T ctor) {
     T[] result = new T[len];

     foreach (inout elem; result) {
         elem = ctor();
     }
     return result;
}


Usage is like so:

auto array = populateArray(50, new MyClass(10));



This also works fine with structures, and technically any other type. 
Although its inefficient for basic scalars, for that use a slice-assignment:

int[]   arr1 = new int[50]; arr1[] = 10;
int[50] arr2;               arr2[] = 10;


-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list