Removing elements from dynamic arrays?
dnewsgroup at billbaxter.com
Mon Oct 30 18:20:58 PST 2006
David Medlock 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 = void;
>> a[3..4] = void;
>> a[3..4] = a[3..3];
>> a = ;
>> a[3..4] = ;
>> delete a;
>> delete a[3..4];
>> The last one compiles, but fills a with garbage.
>> I hope the answer isn't:
>> a = a[0..3] ~ a[4..length];
> From my personal tools library...
> // remove an item from an array
> template drop(T)
> T drop( inout T arr, int which )
> debug if ( which>=arr.length)
> throw new Exception(str.format("Attempt to drop position %s from
> size %s",which,arr.length));
> T result = arr[which];
> int max = arr.length-1;
> for (; which < max; which++ ) arr[which]=arr[which+1];
> arr.length= max;
> return result;
> Even though it returns the array, it modifies it in place.
Thanks David, this seems like the best answer in terms of efficiency,
although I suppose the
a = a[0..3] ~ a[4..length];
could theoretically be pretty similar depending how the compiler
There really should be syntax in the language or at least functions like
the above in the standard library for this (and for removing slices).
Otherwise std::vector starts to look handy compared to D arrays, and you
don't want that! ;-) Built-in arrays are supposed to be easier to use
than library code, after all.
// Erases the element at position pos.
iterator std::vector::erase(iterator pos)
//Erases the range [first, last)
iterator std::vector::erase(iterator first, iterator last)
Other than that, it looks like arrays support a sane syntax for
everything std::vector has, except maybe
which has also been discussed recently.
More information about the Digitalmars-d-learn