How do you remove/insert elements in a dynamic array without allocating?
bearophile
bearophileHUGS at lycos.com
Mon Nov 5 17:27:24 PST 2012
Malte Skarupke:
> 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?
void main() {
auto array = [1, 2, 3, 4, 5];
array.assumeSafeAppend();
foreach (i; 0 .. 10_000_000) {
array.length--;
array ~= i;
}
}
> But neither one works.
And that's good, it was designed that way on purpose :-)
> How do you work with the dynamic array without having to rely
> on the GC all the time?
There are various ways to do it...
> I want something similar to the stl vector, which only
> re-allocates once your array grows past a certain size, not on
> every append.
D arrays already work like this.
Bye,
bearophile
More information about the Digitalmars-d
mailing list