How do you remove/insert elements in a dynamic array without allocating?

Ali Çehreli acehreli at yahoo.com
Mon Nov 5 17:23:23 PST 2012


On 11/05/2012 05:11 PM, Malte Skarupke wrote:
> Following code:
>
> void main()
> {
> import core.memory;
> GC.disable();
> scope(exit) GC.enable();
>
> int[] a = [1, 2, 3, 4, 5];
> foreach(i; 0 .. 1000000000)
> {
> --a.length;
> a ~= i;
> }
> }
>
> That loop will keep on allocating in every iteration until your memory
> is full.
>
> Is there a way to do something similar to this without allocating? I
> have also tried slicing:
> a = a[0 .. $ - 1]; // instead of (--a.length;)
>
> But neither one works.
>
> How do you work with the dynamic array without having to rely on the GC
> all the time? I want something similar to the stl vector, which only
> re-allocates once your array grows past a certain size, not on every
> append.
>
> Thanks!
>
> Malte

I think you want assumeSafeAppend() as explained here:

   http://www.dsource.org/projects/dcollections/wiki/ArrayArticle

Ali


More information about the Digitalmars-d mailing list