Removing elements from dynamic arrays?

David Medlock noone at nowhere.com
Mon Oct 30 05:55:38 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 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.

-DavidM



More information about the Digitalmars-d-learn mailing list