【问题标题】:D language: initializing dynamic multidimensional array best practices?D语言:初始化动态多维数组最佳实践?
【发布时间】:2011-12-14 10:29:54
【问题描述】:

只是好奇这是否是在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 在这种情况下只是一个指针数组)。有没有“更好”的方法来做到这一点(不涉及使用一维数组和自己计算索引)?据我从文档中可以看出,一个连续的多维数组只能在编译时用不可变维度声明,只是想知道我是否遗漏了什么......

【问题讨论】:

    标签: multidimensional-array d


    【解决方案1】:

    您可以新建数组,至少在 D2 中:

    Tile[][] tiles = new Tile[][](height, width);
    

    我相信这是最好的做法。

    【讨论】:

    【解决方案2】:

    您可以通过mallocing 预先设置所有您需要的东西来捏造它

    this(uint width, uint height) {
        void* p = enforce(GC.malloc(Tile.sizeof*width*height),new OutOfMemoryException);
              //allocate all rows at once, throw on returned null
        tiles.length = height;
        foreach (i,ref tilerow; tiles)
            tilerow = cast(Tile[])p[Tile.sizeof*width*i..Tile.sizeof*width*(i+1)];
                    //slice it into the multidimensional array
    }
    

    编辑或使用临时数组来保留下摆以使代码更简洁/不易出错(即隐藏 malloc)

    this(uint width, uint height) {
        Tile[] p = new Tile[height*width]
        tiles.length = height;
        foreach (i,ref tilerow; tiles)
            tilerow = p[width*i..width*(i+1)];
                    //slice it into the multidimensional array
    }
    

    【讨论】:

    • 第一个样本的小注释:您可以使用enforceEx,例如enforceEx!OutOfMemoryError(GC.malloc(Tile.sizeof*width*height));,也不是OutOfMemoryException,而是OutOfMemoryError,这些需要导入到std.exceptioncore.memorycore.exception
    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多