Growing multidimensional dynamic arrays

Ali Çehreli acehreli at yahoo.com
Mon Oct 8 06:38:01 PDT 2012


On 10/08/2012 06:12 AM, KillerSponge wrote:
> Hi all,
>
> This seems like something that should be possible: how do I grow
> multidimensional arrays?
>
> I want something like this:
>
> struct X{ ... };
> X*[][] listOfLists;
> foreach ( x ; otherListOfX ) {
> if ( newListForArbitraryReason ) {
> listOfLists ~= new X*[];
> }
>
> listOfLists[$] ~= x;
> }
>
> Now, this doesn't compile, because I _have_ to give a size to new
> X*[](arbitrary_number), and the listOfLists[$] ~= x; line never works
> (hangs at runtime).
>
> So, how would I go about doing this? My apologies if this is something
> really obvious.

I don't see the need for 'new' nor the use of a pointer, so I will not 
use them (yet): :)

import std.stdio;

struct X
{
     int i;
}

void main()
{
     X[][] listOfLists;

     auto otherListOfX = [ X(1), X(2), X(3) ];
     auto newListForArbitraryReason = true;

     foreach (x; otherListOfX) {
         if (newListForArbitraryReason) {
             X[] newList = [ x ];
             listOfLists ~= newList;
         }
     }

     writeln(listOfLists);
}

The body of foreach can be shorter:

             listOfLists ~= [ x ];

Also note that

- There is no need for the semicolon at the end of the struct definition.

- $ is not a valid index value. The last element is indexed by $-1.

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html


More information about the Digitalmars-d-learn mailing list