Removing elements from dynamic arrays?

Lionello Lunesu lio at lunesu.remove.com
Mon Oct 30 00:18:40 PST 2006


Bill Baxter wrote:
> How do I remove an element from a dynamic array?
> 
>    int[] a = [1,2,3,4,5];
> 
> I tried every syntax I could think of:
> 
>    a[3] = void;
>    a[3..4] = void;
>    a[3..4] = a[3..3];
>    a[3] = [];
>    a[3..4] = [];
>    delete a[3];
>    delete a[3..4];
> 
> The last one compiles, but fills a[0] with garbage.
> 
> I hope the answer isn't:
> 
>    a = a[0..3] ~ a[4..length];
> 
> Thanks!
> --bb

 From a COW (copy on write) standpoint, that last one is the only safe 
one, i.e: a = a[0..x] ~ a[x+1..$]; with 'x' the index of the element you 
want to remove.

If you don't need COW and don't care for the order of the elements, you 
can do this: a[x] = a[$-1]; a.length = a.length - 1; //a.length-- won't work

L.



More information about the Digitalmars-d-learn mailing list