Fast temporary dynamic arrays? (And slicing of them)
bearophile
bearophileHUGS at lycos.com
Tue Sep 7 13:26:25 PDT 2010
Tom Kazimiers:
> But good to know that it would work with backward growing of the
> array - do have you an example of that?
Just created:
import std.stdio: writeln;
import std.c.stdlib: alloca;
void main() {
int n = 30;
alias int T;
enum int initialCapacity = 4;
static assert(initialCapacity > 0);
int len = 0;
int capacity = initialCapacity;
int* ptr = cast(int*)alloca(capacity * T.sizeof);
ptr += initialCapacity - 1; // correct?
foreach_reverse (i; 0 .. n) {
if (i >= capacity) {
alloca(capacity * T.sizeof);
capacity *= 2;
}
ptr--;
*ptr = i;
len++;
}
writeln("len, capacity: ", len, " ", capacity);
auto arr = ptr[0 .. len];
writeln(arr);
}
Beware of stack overflows.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list