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

Malte Skarupke malteskarupke at web.de
Mon Nov 5 17:11:06 PST 2012


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


More information about the Digitalmars-d mailing list