Removing elements from dynamic arrays?

Bill Baxter dnewsgroup at billbaxter.com
Wed Nov 1 00:50:35 PST 2006


Bill Baxter wrote:
> David Medlock wrote:
> 
>> For giggles I posted the conditional version(also public domain):
>>
>> // remove items based on a predicate. returns number of items removed
>> template drop_if(T)
>> {
>>   int drop_if( T[] arr, bool delegate(T)pred )
>>   {
>>     int count = 0, dest=0;
>>     foreach( int index, T val ; arr )
>>     {
>>       if ( pred(val) ) { count++; continue; }
>>       if ( dest !=index ) arr[index] = dest;
>>       dest++;
>>     }
>>     return count;
>>   }
>> }
>>
> 

And here's a better range-dropping version:

// Remove a range of elements from an array in place.
// It is not an error for the range to be empty or for start to be
// greater than end. If so, the array is not modified.
// Out of bounds checks performed only in debug mode.
// Returns: the array for convenience (but it is modified in-place).
// Note: This is an O(n) operation.
template drop_range(T)
{
   T[] drop_range( inout T[] arr, int start, int end )
   {
     debug if ( start>=arr.length || end > arr.length || start<0 || end<0)
         throw new Exception(format("Attempt to drop range %s,%s from 
size %s",start,end,arr.length));
     if (start>=end) return arr;
     size_t len = end-start;
     size_t max = arr.length-len;
     for (; start < max; start++ ) arr[start]=arr[start+len];
     arr.length= max;
     return arr;
   }
}

--bb



More information about the Digitalmars-d-learn mailing list