Deleting an element from an array

nobody somebody at somewhere.com
Tue Feb 3 07:54:23 PST 2009


"Jarrett Billingsley" <jarrett.billingsley at gmail.com> wrote in message 
news:mailman.635.1233675301.22690.digitalmars-d-learn at puremagic.com...
> On Tue, Feb 3, 2009 at 10:14 AM, Frank Benoit
> <keinfarbton at googlemail.com> wrote:
>>
>> arr = arr[ 0 .. lowerBound ] ~ arr[ upperBound .. $ ];
>>
>
> That's simple enough, but inefficient.
>
> Something like this:
>
> import std.c.string; // or import tango.stdc.string;
>
> T[] erase(T)(ref T[] arr, size_t idx)
> {
>    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;
> }

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? 




More information about the Digitalmars-d-learn mailing list