Initialization of dynamic multidimensional array

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 6 13:55:59 PST 2017


On 02/05/2017 12:33 PM, berni wrote:
> With X not known at compile time:
>
>> auto arr = new int[][](X,X);
>> for (int i=0;i<X;i++)
>>   for (int j=0;j<X;j++)
>>     arr[i][j] = -1;
>
> Is there anything better for this? I mean, the program will fill the
> array with zeroes, just to overwrite all of them with -1. That's wasted
> execution time and doesn't feel D-ish to me.

Here is something that returns the tail as dynamic array. (Otherwise, 
being a value type, the whole static array would be copied out of the 
function):

template makeMulDim(dims...) {
     template MultDimType(T, dims...) {
         static if (dims.length == 0) {
             alias MultDimType = T;
         } else static if (dims.length == 1) {
             alias MultDimType = T[];
         } else {
             alias MultDimType = MultDimType!(T[dims[0]], dims[1..$]);
         }
     }

     auto makeMulDim(T)(T initValue) {
         import std.algorithm : fold;

         const elementCount = [ dims ].fold!((a, b) => a * b);
         auto storage = new T[](elementCount);
         storage[] = initValue;
         return cast(MultDimType!(T, dims))storage;
     }
}

unittest {
     auto arr = makeMulDim!(2, 3, 4)(1.1);
     static assert (is (typeof(arr) == double[2][3][]));
}

void main() {
     import std.stdio;

     auto arr = makeMulDim!(2, 3, 4)(-1);
     pragma(msg, typeof(arr));
     arr[3][2][1] = 42;
     writefln("%(%s\n%)", arr);
}

So, the returned type in main is int[2][3][].

Ali



More information about the Digitalmars-d-learn mailing list