remove from array

torhu fake at address.dude
Tue Feb 27 16:13:31 PST 2007


Thorsten wrote:
>> <totaly untested code>
>> 
>> T[] Remove(T)(T[] arr, int i)
>> {
>>    return i==arr.length-1 ? arr[0..$-1] : arr[0..i] ~ arr[i+1 .. $];
>> }
> 
> Sorry, I tried that, and it is too expensive !!
> Because it creates about 3 temporary instances.
> I would say :
> 
> void Remove(T)(inout T[] arr, int i)
> {
>   for(uint j = i;j < arr.length-1;++j)
>     arr[j] = arr[j+1];
>   arr.length = arr.length - 1;
> }
> 
> can someone accelerate this ???

I see Bill already told you about cashew, but here's an answer anyway.

You can use memmove to do the copying.  Using memmove also seems to be 
the fastest way to insert elements in the middle of an array, if you 
need that too.

void Remove(T)(inout T[] arr, int i)
{
   assert(arr && i < arr.length);
   memmove(arr.ptr + i, arr.ptr + i + 1, (arr.length - i - 1) * T.sizeof);
   arr.length = arr.length - 1;
}

If you don't care about the order, you can of course just do this:

arr[i] = arr[$-1];
arr.length = arr.length - 1;



More information about the Digitalmars-d mailing list