data containers

Steven Schveighoffer schveiguy at yahoo.com
Fri Jul 4 06:45:49 PDT 2008


"Moritz" wrote
> So now I have a two dimensional array ready for my classes, but sadly, I 
> cant find any information on how classes can be stored in a 
> multidimensional array and how I can use the instances stored there.
>
> Ive just guessed and typed:
>
> int add_element(ScreenElement new_element, uint layer)
> {
> if(layer <= layer_count)
> {
> ScreenElement[] single_layer = layer_map[layer];
> single_layer ~= new_element;
> }
> else
> {
> writefln("cant insert ScreenElement into non existing layer");
> }
> return 0;
> }
>
> Sadly, this doesnt work, I get an Error: ArrayBoundsError upon inserting.
> Can anyone tell me how this is done, and maybe even where I can find usful 
> examples for more cmplex uses of arrays in D?
>
> My biggest problem ATM is the lack of good tutorials or examples, it seems 
> that D is no easy language to get started with, once you want to do more 
> than basics :-(

To help you understand, think of it this way:

ScreenElement[][] is really a dynamic array of dynamic arrays.  In 
otherwords, it means:

(ScreenElement[])[].

So this starts out empty.  In order to initialize it, say to size 5, you 
should do:

ScreenElement[][] layer_map = new ScreenElement[][5];

Now, the map has 5 empty ScreenElement[] arrays in it.

It's a lot easier to understand if you alias the ScreenElement[] type:

alias ScreenElement[] layer;

layer[] layer_map = new layer[5];

The thing about D that I like is that it is completely consistent in this 
regard.  There are no 'special' cases, everything is broken down to the same 
simple case.  Once you understand that, multi-dimensional arrays become 
really easy.

-Steve 




More information about the Digitalmars-d-learn mailing list