multidimensional array setting/slicing?

Steven Schveighoffer schveiguy at yahoo.com
Mon Jul 28 07:34:11 PDT 2008


"Saaa" wrote
> Thanks, the code now looks like this (and works :)
>
> int array[][];
> array.length=10;
> foreach(ref a; array)
>  a.length = 5;
>
> int array2[][];

You can comment out these lines:

/*
> array2.length=2;
> foreach(ref a; array)
>  a.length = 6;
*/

>
> array2=[[1,2,3,4],[5,6,7,8]];

could be:

auto array2=[[1,2,3,4],[5,6,7,8]];

and get rid of the array2 declaration above.

At this point, you have thrown away all your work you did to set the lengths 
in array2 :)

Note that setting array2 this way just changes the array to point to the 
array literal, it doesn't copy data from the literal.

>
> foreach(i, ref a; array[2..2+array2.length])
> a[1..1+array2[i].length] = array2[i];
>
> writefln(array2);
> writefln(array);
>
> [[1,2,3,4],[5,6,7,8]]
> [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,1,2,3,4,0],[0,5,6,7,8,0],[0,0,0,0,0,0],
> [0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
> --------------------------
> //And for 3D:
>
> int array[][][];
> array.length=6;
> foreach(ref a; array)
> {
>  a.length = 6;
>  foreach(ref b; a)
>   b.length = 6;
> }
>
> int array2[][][];

ditto here:
/*
> array2.length=2;
> foreach(ref a; array2)
> {
>  a.length = 2;
>  foreach(ref b; a)
>   b.length = 2;
> }
>
*/

>
> array2=[[[1,2],[5,6]],[[9,9],[8,7]]];

could be:

auto array2=[[[1,2],[5,6]],[[9,9],[8,7]]];

>
> foreach(i, ref a; array[2..2+array2.length])
> foreach(ii, ref b; a[2..2+array2[0].length])
>  b[1..1+array2[ii].length] = array2[i][ii];
>
> writefln(array2);
> writefln(array);
> --------------------------
> ... erm I barely follow it myself :/

Yeah, it's not really that readable :)  Perhaps encapsulating it into a 
function would be more readable.

>
> I think array can be static and maybe array2 will be as well and I'll 
> manually keep the x,y and z sizes and do normal for-loops over them.

static arrays are different than dynamic arrays, in that they are contiguous 
memory :)  But I think you will still need to set the data in the same way.

-Steve 




More information about the Digitalmars-d-learn mailing list