代码之家  ›  专栏  ›  技术社区  ›  Jacob Birkett

std.algorithm.remove()复制数组项?

  •  2
  • Jacob Birkett  · 技术社区  · 7 年前

    我有一个数组,需要按索引从中删除项出于某种原因,它会复制数组中的其他项以取代已删除项这是一个例子。

    import std.stdio: writeln;
    import std.algorithm: remove;
    
    void main() {
        string[string] assocArray = [
            "firstvalue": "Number 1",
            "secondvalue": "Number 2",
            "thirdvalue": "Number 3",
            "fourthvalue": "Number 4",
            "fifthvalue": "Number 5",
            "sixthvalue": "Number 6",
        ];
    
        string[] assocArrayKeys = assocArray.keys(); // I know these aren't in the same order as the literal.
    
        writeln(assocArrayKeys);
        // ["thirdvalue", "fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue"]
    
        assocArrayKeys.remove(0);
        assocArrayKeys.remove(5);
    
        writeln(assocArrayKeys);
        // ["fourthvalue", "fifthvalue", "sixthvalue", "firstvalue", "secondvalue", "secondvalue"]
        // It did remove them, but there are now two "secondvalue"s.
    }
    

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jacob Birkett    7 年前

    这个问题有点傻有人指出,在文件中,它说,它必须重新分配给自己。

    请注意,remove不会直接更改原始范围的长度;相反,它会返回缩短的范围如果未将其返回值指定给原始范围,则原始范围将保留其原始长度,尽管其内容已更改。

    资料来源: https://dlang.org/library/std/algorithm/mutation/remove.html

    解决方法如下:

    assocArraykeys = assocArrayKeys.remove(0);
    assocArrayKeys = assocArrayKeys.remove(5);
    

    但这对我来说有点愚蠢和不友好,因为它在 std.algorithm.mutation . 关键字: 突变 .