Search code examples
arraysd

How to delete an element from an array in D


Concatenating an element x to an array items is easy in D, it's as if it were an array list:

arr ~= x;

but how do I remove an element at index i from items?

(Caveat: If I remove an element and then add a new element, the array must not be reallocated. So a simple slice won't work.)


Update:

Based on CyberShadow's answer about using assumeSafeAppend, I wrote this code:

static void removeAt(T)(ref T[] arr, size_t index)
{
    foreach (i, ref item; arr[index .. $ - 1])
        item = arr[i + 1];
    arr = arr[0 .. $ - 1];
    arr.assumeSafeAppend();
}

However, the problem happens when you have something like:

auto superArr = [0, 1, 2, 3, 4]; //Must not be modified
auto arr = superArr[0 .. $ - 1];
writeln(superArr);
arr.removeAt(0);    //Should copy the slice and modify the copy
writeln(superArr);  //but obviously doesn't

The base array of slice should not be modified if an element is removed from the slice; instead, the slice needs to be copied.

But I have no way of knowing if an array is a slice of a bigger array... so that doesn't work.

Any suggestions?


Solution

  • (Caveat: If I remove an element and then add a new element, the array must not be reallocated. So a simple slice won't work.)

    The assumeSafeAppend function will tell the runtime not to reallocate the array when appending to it (i.e. it is an affirmation from the user that there aren't other slices which might be stomped by an append).

    remove from std.algorithm does an in-place remove. If you're using std.container, there's also Array.linearRemove.