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?
In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.
We explored using for loops with one-dimensional arrays. Now let's jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another.
Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.
To loop over two dimensional array in Java you can use two for loops. Each loop uses an index. Index of outer for loop refers to the rows, and inner loop refers to the columns. You can then get each element from the array using the combination of row and column indexes.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With