Removing elements from dynamic arrays?

Sean Kelly sean at f4.ca
Mon Oct 30 09:24:11 PST 2006


Chris Nicholson-Sauls wrote:
> 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;

Unfortunately, I think this is illegal.  See my thread in this group 
entitled "Removing an array element in order."


Sean



More information about the Digitalmars-d-learn mailing list