2d array

Era Scarecrow rtcvb32 at yahoo.com
Sat Jan 1 01:19:33 UTC 2022


On Saturday, 1 January 2022 at 00:19:56 UTC, chopchop wrote:
> I have worked on a little FOSS project (I will ask later for 
> code review), I have noticed some limitation on 2d arrays. I 
> haven't found the answers on the forum
>
> 1) I can not initialize a 2d array in the body of the class,
> ```d
> class A
> {
>   Stuff[][] array2d = Stuff.ONE;
> }
> ```
> One must do that in the ctor

  If the size is statically known you probably can, however you'd 
be doing it as CTFE.

```d
struct Chess {
   static int[8][8] grid = makeGrid();

   auto makeGrid() {
     int[8][8] tmp;
     //build grid stuff
     return tmp;
   }
}
```

I forget if class variables can be instantiated by default in a 
similar way or not (*like working in Java*).

> 2) The following code yields Error: cannot implicitly convert 
> expression `3` of type `int` to `int[20][]`
> ```d
> import std;
> void main()
> {
>     writeln("Hello D");
>     int[20][20] array2d;
>     array2d = 3;
> }
> ```
> What I would expect, of course, is to automatically iterate 
> through the entire 2d array and set each (i,j) pair to "3".

Trying array2d array2d[] array2d[][] all result in the same 
error. I do agree being able to bulk fill or zeroize might be 
nice in some cases. But it's just a little more typing to get the 
same result.

  I wonder if a template mixin would fix this.

```d
foreach(ref y; array2d)
   y[]=3;
```

> 3) Similarly, it would be nice to have a foreach as follow:
> ```d
> foreach ( cell; array2d)// where i = 0 for all j then i = 1 for 
> all j, etc
> ```

So like this? Alternatively iota might also do the job.
```d
foreach(i, ref j; array2d)
   j[]=i;
```

> I guess I can build something with opApply but... Could even be 
> something like
> ```d
> foreach (i, j, cell; array2)
> ```

  Hmmm. Default behavior probably is better as is. Consider you 
can alias stuff to build larger stuff. So let's assume i am doing 
some chess stuff.

```d
  alias cell=int;
  alias row=cell[8];
  alias grid=row[8];

  grid board;
```

  Now let's assume i did something like... move piece and 
reference it wrong.

```d
auto movePiece(int x,int y,int x2,int y2) {
   //do checks
   board[x2][y2]=board[x][y];

   //clear piece
   board=0; //should be board[x][y]=0;
}
```

  With default behavior and being more explicit you'd catch a 
simple bug instead of tracing your code for what compiled 
correctly. it's one of the reasons assignment in if statements is 
disallowed as it's easy to mess up. Same for forcibly casting 
rather than assuming down-casting or other is fine.


More information about the Digitalmars-d mailing list