Dynamic arrays in D 1.0
Bill Baxter
dnewsgroup at billbaxter.com
Sun May 11 13:32:51 PDT 2008
Janice Caron wrote:
> On 11/05/2008, Bill Baxter <dnewsgroup at billbaxter.com> wrote:
>> Janice Caron wrote:
>
>>> To erase the elements from index i to index j in place:
>> It can be done more efficiently using memmove to shift contents down. Also
>> if you're dropping the tail end, you can just change .length. Cashew's erase
>> routine (called "dropRange") does both.
>
> OK, how about this, using std.algorithm.copy:
>
> array = copy(array[j..$], array[i..$]);
> array = array[0..$+i-j];
>
> The copy is done in-place, like memmove(), but without the danger of
> buffer overrun.
Std.algorithm's copy(), in its current form, will be less efficient
because it copies elements one-at-a-time in a loop. This was what the
first version of Cashew did, but it was benchmarked and found that
memmove is faster.
Of course, std.algorithm.copy could probably be tweaked to use memmove
when possible, and then that would be just as good. But right now it
isn't.
Anyway, the existence of such subtleties is why things like erase should
just be in the darn standard library so the problem only has to be
solved once.
> You still need the second line to change the length though.
>
> You can even do it ONE LINE, but I have to confess, the code looks
> pretty obfuscated.
>
> array = array[0..$-copy(array[j..$], array[i..$]).length];
Yeh, don't do that. :-)
--bb
More information about the Digitalmars-d
mailing list