Removing elements from dynamic arrays?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Oct 30 06:19:07 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

Assuming you mean remove as in extract and throw away the item at a given index, then yes 
that last one is the only way.  In Cashew this is abstracted to array.removeIndex(size_t). 
  I really can't think of any other way it could be done, though...

Except for maybe:
# a[3 .. a.length - 1] = a[4 .. a.length];
# a.length = a.length - 1;

Hrm, not really any better.  Or maybe, using Cashew (but avoiding .removeIndex):
# a[3 .. a.length].rotl;
# a.pop;

Essentially, the same thing anyway.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-learn mailing list