2

我有一个数组,我需要按索引从中删除项目。由于某种原因,它复制了数组中的其他项目以取代已删除项目的位置。这是该问题的一个示例。

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.
}

任何帮助,将不胜感激。

4

1 回答 1

2

这是一个有点愚蠢的问题。有人指出,在文档中,它说它必须重新分配给它自己。

注意remove不会直接改变原始范围的长度;相反,它返回缩短的范围。如果其返回值未分配给原始范围,则原始范围将保留其原始长度,尽管其内容会发生变化。

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

解决方法如下:

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

这对我来说似乎有点愚蠢和不直观,因为它在std.algorithm.mutation. 关键词:突变

于 2018-07-24T05:19:49.687 回答