开发者

D2: setting array dimensions at runtime

How do you set the dimension of an array when you don't yet know it at compile time?

For instance: byte[][] a = new byte[size][size]; The compiler does not allow it. How am I supposed to initialize the grid? Manually?

byte[] a1;
for (int i; i < size; i++) {
     a1 ~= 0;
} 
byte[][] a2; 
for (int i; i < size; i++) {
     a2 ~= a1;
} 

Please tell me there is a simpler way.

Edit: this also works, but it i开发者_Python百科s still hopelessly primitive, and slow

byte[][] a3; 
a3.length = size;
for (int i; i < size; i++) {
     a3[i].length = size;
} 


Don't going into depths, here is an example of initializing multidimensional dynamic array in D:

auto a = new int[][](4, 4);

Edit: here goes more complete example (showing that you can initialize array during runtime to avoid confusion):

int x = 3, y = 4, z = 5;
auto a = new byte[][][](x, y, z);

Stdout(a[0][0].length).newline; // prints 5
a[0][0].length = 10;
Stdout(a[0][0].length).newline; // prints 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜