Why is std.algorithm so complicated to use?

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 15 15:39:04 PDT 2012


On Sunday, July 15, 2012 18:24:47 Andrei Alexandrescu wrote:
> On 7/15/12 6:22 PM, Mehrdad wrote:
> > On Sunday, 15 July 2012 at 22:03:33 UTC, Jonathan M Davis wrote:
> >> auto arr = [10, 22, 19, 4, 6];
> >> arr = remove(arr, 3);
> >> assert(arr == [10, 22, 19, 6]);
> > 
> > Yeah, the problem is that this reallocates...
> 
> doesn't

Yeah. It just slices. remove moves the elements over by one, and returns a 
slice of the range which is shorter by the number of elements removed. And 
since assigning one array is just assigning the ptr and length properties, 
there's no copying of the elements there, and no reallocations are required 
anywhere.

Now, if you want to append to the array afterwards, then you're going to get a 
reallocation (unless you know that there are no other arrays referring to 
anything after the returned slice, in which case, you can use assumeSafeAppend 
make it so that it doesn't reallocate). But the removal involves no 
reallocations at all.

- Jonathan M Davis


More information about the Digitalmars-d mailing list