D语言:初始化动态多维数组最佳实践?
只是好奇这是否是在 D 中初始化动态多维数组的最佳实践。他们的语言参考中有一个关于数组的部分,但我不太确定它是否超出了我想要完成的任务。
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
(或者类似典型的 for (y=0;y
我对此的担忧是,它单独重新分配数组的每一行,而不是一次性重新分配整个块,所以我不知道这是否会导致过多的内存洗牌。另外,我相信它不能保证是连续的(因为在这种情况下 tiles 只是一个指针数组)。有没有“更好”的方法来做到这一点(不涉及使用一维数组并自己计算索引)?据我从文档中可以看出,连续的多维数组只能在编译时用不可变的维度声明,只是想知道我是否遗漏了一些东西......
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
(or an equivalent alternative like a typical for (y=0;y<height;y++) loop).
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以新建数组,至少在 D2 中:
我相信这是最佳实践。
You can new the array, at least in D2:
I believe this is the best practice.
你可以通过
malloc
预先编辑你需要的所有东西来捏造它,或者使用临时数组来保留下摆以获得更干净/更少错误的代码(即隐藏malloc)
you can fudge it by
malloc
ing every thing you need upfrontEDIT or use a temporary array to keep hem in for cleaner/less bugprone code (i.e. hide the malloc)