Deleting an element from an array

Saaa empty at needmail.com
Wed Feb 4 11:05:22 PST 2009


Please tell me when I got something wrong : )

>>>
>>> arr = arr[ 0 .. lowerBound ] ~ arr[ upperBound .. $ ];
>>>
>>
>> That's simple enough, but inefficient.
Because it loops over arr.length-2 and copies the pointers.
Will the compiler optimize by not copying the [0..lowerbound] part?
And will the compiler get that it can do
arr[x]=arr[x+difference]
for the [upperBound .. $] part
iso creating a temporary array (not doing in place is what this is called I 
think)

>>
>> Something like this:
>>
>> import std.c.string; // or import tango.stdc.string;
>>
>> T[] erase(T)(ref T[] arr, size_t idx)
Where can I read about this variaidic type usage... looks awesome
And, when do I need to use size_t?

>> {
>>    if(arr.length == 0)
>>        throw new Exception("FAILCOPTER");
>>
>>    if(idx < arr.length - 1)
>>        memmove(&arr[idx], &arr[idx + 1], T.sizeof * (arr.length - idx - 
>> 1));
>>
>>    arr.length = arr.length - 1;
>>    return arr;
>> }
What you are doing here is the same as the above but forcing the two
optimizations.

>
> Let's see if I understand memmove..
> The way it's used here, it copies the tail of an array onto that same 
> array, only starting one index earlier, thus removing the undesired 
> element?
> Neat.
>
> However I just realized that order does not matter in the array I'm using, 
> so I guess I could use something like:
> arr[ind] = arr[$-1];
> arr.length = arr.length -1;
> Seeing how this only copies once, I'm guessing this is more efficient?
This will copy the pointer of the last element to the to-be-replaced element
Will the GC actually delete the element with the unreferenced pointer 
arr[ind].ptr?





More information about the Digitalmars-d-learn mailing list