D语言:初始化动态多维数组最佳实践? [英] D language: initializing dynamic multidimensional array best practices?
问题描述
请问这是否是在 D 中初始化动态多维数组的最佳实践。在他们的语言参考中有关于数组的部分,但我不确定它是否超出了我要完成的工作。
Just curious if this is the best practice for initializing a dynamic, multidimensional array in D. There is a section on arrays in their language reference, but I'm not quite sure if it goes over what I'm trying to accomplish.
class Map {
Tile[][] tiles;
this(uint width, uint height) {
tiles.length = height;
foreach (ref tilerow; tiles)
tilerow.length = width;
}
}
Map map1 = new Map(5000, 3000); // values determined at runtime
(或类似的替代方法,例如(y = 0; y< ; height; y ++)循环)。
(or an equivalent alternative like a typical for (y=0;y<height;y++) loop).
对此我的担心是,它会分别重新分配数组的每一行,而不是一次重新分配整个块,所以我不这样做不知道这是否会导致过多的内存改组。另外,我相信不能保证它是连续的(在这种情况下,由于 tiles 只是一个指针数组)。是否有任何更好的方法(不涉及使用一维数组和自己计算索引)?据我所知,在编译时只能用不可变的维声明连续的多维数组,只是想知道我是否缺少某些东西...
My concern with this is that it reallocates each row of the array separately rather than the whole chunk all at once, so I don't know if this will lead to too much memory shuffling. Also, I believe it's not guaranteed to be contiguous (since tiles is just an array of pointers in this case). Is there any "better" way to do this (that doesn't involve using a single-dimensional array and computing the index myself)? As far as I can tell from the docs a contiguous multidimensional array can only be declared with immutable dimensions at compile time, just wondering if I'm missing something...
推荐答案
您可以至少在D2中 new 数组:
You can new the array, at least in D2:
Tile[][] tiles = new Tile[][](height, width);
我相信这是最佳做法。
这篇关于D语言:初始化动态多维数组最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!