implementing stacks using dynamic arrays

Boyko Bantchev Boyko_member at pathlink.com
Sun Apr 9 05:58:31 PDT 2006


Hello all,

The documentation describes ~= as (dynamic) array concatenation.
I've noticed that it can also add an element to a dynamic
array, as e.g. in:
int[] a;
int t;
..
a ~= t;
which makes a beautiful generic push operation for stacks.
But, then, what about the pop operation?  As far as I know,
it is not directly supported in D, or am I missing something?
Currently, I use the following:

template Pop(T)  {
T pop(inout T[] arr)  {
uint n = arr.length;
assert(n>0);
T t = arr[--n];
arr.length = n;
return t;
}
}

but it seems too clunky.  I would much prefer to have
a single operation built in the language, which pops an
element or throws an exception if the array is empty.
In view of D having dynamic arrays anyway, this seems
a reasonable expectation,.

I would be glad to know other people's opinions on the above.

Regards,
Boyko





More information about the Digitalmars-d mailing list