Removing elements from dynamic arrays?
Bill Baxter
dnewsgroup at billbaxter.com
Wed Nov 1 00:39:41 PST 2006
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 the range-dropping version:
template drop_range(T)
{
void drop_range( inout T[] arr, int start, int end )
{
debug if ( start>=arr.length && end > arr.length)
throw new Exception(format("Attempt to drop range %s,%s from
size %s",start,end,arr.length));
if (start>=end) return;
size_t len = end-start;
size_t max = arr.length-len;
for (; start < max; start++ ) arr[start]=arr[start+len];
arr.length= max;
}
}
More information about the Digitalmars-d-learn
mailing list