Rectangular Arrays
Bill Baxter
dnewsgroup at billbaxter.com
Thu Feb 22 22:37:15 PST 2007
Another Roadside Attraction wrote:
> I'm learning D by writing a logic game with a grid-shaped board. If possible, I'd like to use a rectangular array for the board, but I'd like to define the width of the board at runtime when I instantiate the class. Ideally, I'd like to do something like this:
>
> public class Board {
>
> private Piece[,] grid;
>
> public this(uint width) {
> grid = new Piece[width,width];
> }
>
> }
>
> But that doesn't compile. It looks like the dimensions of rectangular arrays has to be known at compile-time. Is that right, or am I missing something?
>
> I've also tried declaring the array as an ordinary multi-dimensional array, but this doesn't compile either:
>
> public class Board {
>
> private Piece[][] grid;
>
> public this(uint width) {
> grid = new Piece[width][width];
> }
>
> }
>
> What's the best way to write this code? As I expand on this project, I plan on incorporating some time-consuming algorithms (think, n-Queens problem), so I'd prefer to use the most efficent data structure possible for the board.
>
> Thanks!!
>
> --ARA
D doesn't have rectangular arrays at the moment. But you can init a
multi-dim ragged array.
http://www.digitalmars.com/d/expression.html#NewExpression
int[][][] bar = new int[][][](5,20,30);
or
auto bar = new int[][][](5,20,30);
I have some nd rectangular array at
http://www.dsource.org/projects/multiarray
but it sounds like for your purposes the ragged array will be sufficient.
--bb
More information about the Digitalmars-d-learn
mailing list