Multidimensional foreach

Bill Baxter wbaxter at gmail.com
Fri Dec 18 10:49:31 PST 2009


On Fri, Dec 18, 2009 at 5:17 AM, Simen kjaeraas <simen.kjaras at gmail.com> wrote:
> Simen kjaeraas <simen.kjaras at gmail.com> wrote:
>
>> I have a function that returns an N-dimensional array, where N is a
>> template parameter. Now I want to run a foreach loop through each
>> element of this array. Is there a known and tested way to do this,
>> or should I write my own templates to do it?
>
> I wrote this implementation. Now, to get some meaningful indices
> out of it. Do D2's ranges even support that? Oh, and I probably
> need to rewrite it in terms of an index instead of slices to get
> that working. Bah.
>
> Ideas? Comments? Death threats?

I think you need to explain more what you are hoping to accomplish.
In general there are two ways to store multidimensional data:

1) jagged - with arrays of arrays.  This is the method directly
supported by D arrays.
    With this accessing each element requires as many indirections as
there are dimensions.
    But for large arrays, this is more friendly to memory use because
the data doesn't have to be in one huge contiguous chunk

2) rectangular - with indexing into a chunk of memory.  This method is
directly supported by some languages like C#, but not D.
    Accessing each element requires just one indirection but a bit of
offset computation.
    Very large arrays may have trouble fitting in available memory.
   (See this very old proposal for adding them to D:
http://homepages.uni-regensburg.de/~nen10015/documents/D-multidimarray.html)

Generally if your plan is to do math on these arrays, method 2 is
better supported by existing math libraries.
So what do you plan to do with these?  You may be better off
implementing a rectangular style multi-dim array type than trying to
use D's built-in.  Or look at the multi-dim array types written by
Fawzi or myself.

--bb


More information about the Digitalmars-d-learn mailing list