Create a foreach-able struct? Multi-dimensional even?

Heywood Floyd soul8o8 at gmail.com
Thu Aug 25 05:48:35 PDT 2011


Christophe Wrote:

> > Still, is the multi-dimensional part possible?
> 
> Sure, you have to make an opApply that takes several parameters in its 
> delegate.
> An exemple:
> 
> struct TwoDArray(int nx, int ny)
> {
>   int[nx][ny] data;
> 
>   int opApply(int delegate(ref int i, ref int j, ref int cell)
>     {
>       foreach (i; 0..nx)
>         foreach (j; 0..ny)
>           {
>             int result = dg(i, j, data[i][j]);
>             if (result != 0) return result;
>           }
>        return 0;
>     }
> }
> 
> 
> // this program prints a multiplication table:
> int main()
> {
>   TwoDArray!(10, 10) data;
>   
>   foreach(i, j, ref cell; data)
>     {
>       cell = i * j;
>     }
> 
>   foreach(i, j, cell; data)
>     {
>       writefln("%s * %s = %s", i, j, cell);
>     }
>   return 0;
> }
> 


Ha! Beautiful, thanks!!



More information about the Digitalmars-d-learn mailing list