delete an element from an array

Michael Rynn michaelrynn at optusnet.com.au
Tue Oct 26 05:10:49 PDT 2010


On Sun, 24 Oct 2010 13:02:24 +0200, Adam Cigánek wrote:

> Hello,
> 
> Is there a function in the standard library to delete an element from an
> array (or range)? Something like:
> 
>   auto a = [1, 2, 3, 4, 5, 6];
>   auto b = delete(a, 4);
> 
>   assert([1, 2, 3, 4, 6] == b);
> 
> I've noticed there is eliminate in std.algorithm, which seems to be
> doing just that, but it's commented out.
> 
> It's not difficult to roll my own, (with the help of indexOf and
> remove), but I thought that this is pretty common operation so it should
> be in the standard library.
> 
> 
In D2 std.array has 

void replace(T, Range)(ref T[] array, size_t from, size_t to, Range stuff);
	and a delete can be done by passing null as stuff.

This multipurpose template will replace with whatever gets passed as stuff, including null.
import std.array;
...
auto a = [1, 2, 3, 4, 5, 6];
replace(a, 4, 5, null);    // delete slice 4..5
assert([1, 2, 3, 4, 6] == a);


The documentation also shows comments for code that has been commented out.
eg Erases element from array at index from.  (code is commented out).

Shows a need for doc comments to be commented out with the code they refer to, 
as this confused me for a bit, until I found that the 4 argument version is the only working one.





More information about the Digitalmars-d-learn mailing list