Is there a better way to iterate over a multidimensional array?

I have a dynamic 3d array of numbers, and currently I am doing this as usual in C:

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

It looks pretty ugly. Is there a shorter and possibly more elegant way to do this in D?

+6
multidimensional-array d
source share
2 answers

Using foreach is probably the most idiomatic approach in D. It can be iterated both by index and by value or value.

 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); } } 
+9
source share
 import std.array; foreach(el;join(join(arr3))){ writeln (el); } 

however, this way you cannot distinguish which lower array you are accessing (unless you add a separator as the second argument to the join function)

0
source share

All Articles