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

Christophe travert at phare.normalesup.org
Thu Aug 25 03:33:20 PDT 2011


> 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;
}



More information about the Digitalmars-d-learn mailing list