Search code examples
multidimensional-arrayd

Is there a better way to iterate over multidimensional array?


I have a dynamic 3d array of numbers and currently I'm doing it like I usually would in C:

for (auto i = 0; i < size; i++) {
    for (auto j = 0; j < size; j++) {
        for (auto k = 0; k < size; k++) {
            ...
        }
    }
}

Looks pretty ugly. Is there a shorter and maybe more "elegant" way of doing this in D?


Solution

  • Using foreach is probably most idiomatic approach in D. It is possible to iterate by both index and value or value only.

    import std.stdio;
    
    void main () {
    
    auto arr3 = [ [[1 ,2 ,3 ]], [[4 ,5 ,6 ]], [[7 , 8, 9]], 
                  [[11,12,13]], [[14,15,16]], [[17,18,19]] ];
    
        foreach (index3, arr2; arr3)
        foreach (index2, arr1; arr2)
        foreach (index1, val ; arr1) {
            assert (val == arr3[index3][index2][index1]);
            writeln (val);
        }
    }