string[int[][]] ??

Steven Schveighoffer schveiguy at yahoo.com
Thu Jul 22 14:52:37 PDT 2010


On Thu, 22 Jul 2010 17:21:15 -0400, dcoder <blah at blah.com> wrote:

> == Quote from Steven Schveighoffer (schveiguy at yahoo.com)'s article
>> This is what I think you should use:
>> string[int[2]]
>> Although, I'm not sure if you can then do something like:
>> chessboard[[0,1]] = "Rook";
>> as the [0, 1] is typed as a dynamic array.  If it does work, it may
>> actually create [0,1] on the heap and then pass it as an int[2], which
>> would suck.
>
> board[[0,0]] = "Rook";
>
> seems to work.  thanks.  But, the foreach loop looks strange.  It looks  
> like it
> takes the hash value of the key:
>
>  string[int[2]] board;
>
>   board[[0,0]] = "Rook";
>   board[[0,1]] = "Knight";
>
>   foreach( pos, val; board) {
>     writefln( "%s: %s", pos, val);
>   }
>
>
> Output:
>
> 2 9903680: Knight
> 2 9903696: Rook

It may be represented properly inside the AA.  There are currently some  
bugs with AA's and using foreach.

>> Or, if you know how big your chessboard is (8x8 isn't a lot of memory),
>> then:
>> string[8][8] chessboard;
>> is pretty straightforward :)
>
> Yes it is :)  Hehe....
>
>
> Now, what if I wanted to do the following:
>
>
> class Board {
>   string[][] positions;
>
>   this( int x, y) {
>       // set the size of positions
>   }
> }
>
> I want positions to internally represent a chess board, a tic tac toe  
> board, or a
> Connect Four board, etc...
>
> But, I want to fix the dimensions of the board when the board gets  
> instantiated,
> so that I can have the compiler do all the work of bounds checking for  
> me.  I can
> create class variables maxx, maxy and access functions that check  
> against the
> variables, but I'm wondering if there's a way to make the compiler do it  
> for you.
>
> Is there a way?

If you want it to be "compile-time-decided" but not hard-coded to 8x8:

class Board(int width, int height)
{
    string[width][height] positions;
}

Then you do:

auto brd = new Board!(8, 8);

-Steve


More information about the Digitalmars-d-learn mailing list