Removing elements from dynamic arrays?
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Mon Oct 30 12:38:15 PST 2006
Sean Kelly wrote:
> 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
Ah. Most likely because of pointer corruption from assigning a slice of an array into
that same array. Should still be doable with a little magic, but probably more trouble
than its worth. Yet another reason I think Phobos needs an array utils module like that
in my Cashew or like Oskar's work... or any of the others that have popped up now and
then. Even some of std.string could be abstracted into "std.array" for cases where
Unicode compatability is not neccessary (closed systems using strictly char[] or dchar[],
for example).
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list