D: initialization of advanced dynamic multidimensional array methods?

Just wondering if this is the best practice for initializing a dynamic multidimensional array in D. There is a section on arrays in their language links, but I'm not quite sure if this is what I'm trying to accomplish.

class Map { Tile[][] tiles; this(uint width, uint height) { tiles.length = height; foreach (ref tilerow; tiles) tilerow.length = width; } } Map map1 = new Map(5000, 3000); // values determined at runtime 

(or the equivalent alternative, as usual for a loop (y = 0; y <height; y ++)).

My concern about this is that it redistributes each row of the array separately, and not the entire fragment at the same time, so I donโ€™t know if this will lead to too much memory shuffling. In addition, I believe that this is not guaranteed to be contiguous (since tiles are just an array of pointers in this case). Is there a โ€œbetterโ€ way to do this (this does not involve using a one-dimensional array and calculating the index itself)? As far as I can tell from the docs, an adjacent multidimensional array can only be declared with immutable dimensions at compile time, just wondering if something is missing ...

+8
multidimensional-array d
source share
2 answers

You can create a new array, at least in D2:

 Tile[][] tiles = new Tile[][](height, width); 

I think this is the best practice.

+17
source share

you can lure him malloc for everything you need in advance

 this(uint width, uint height) { void* p = enforce(GC.malloc(Tile.sizeof*width*height),new OutOfMemoryException); //allocate all rows at once, throw on returned null tiles.length = height; foreach (i,ref tilerow; tiles) tilerow = cast(Tile[])p[Tile.sizeof*width*i..Tile.sizeof*width*(i+1)]; //slice it into the multidimensional array } 

EDIT or use a temporary array to clean up the code for a cleaner / smaller error code (i.e. hide malloc)

 this(uint width, uint height) { Tile[] p = new Tile[height*width] tiles.length = height; foreach (i,ref tilerow; tiles) tilerow = p[width*i..width*(i+1)]; //slice it into the multidimensional array } 
+3
source share

All Articles