Reputation: 6926
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?
Upvotes: 6
Views: 294
Reputation: 48196
import std.array;
foreach(el;join(join(arr3))){
writeln (el);
}
however this way you can't differentiate between which lower array you access (unless you add a separator as second argument in the join functions)
Upvotes: 0
Reputation: 2657
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);
}
}
Upvotes: 9