implementing stacks using dynamic arrays

John Demme me at teqdruid.com
Sun Apr 9 06:27:25 PDT 2006


Boyko Bantchev wrote:

> 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

You can use array slicing to do it:
int[] a;
int t;
...
a ~= t;
...
t = a[$-1]; //Get the last element
a = a[0..$-1]; //Slice off the last element

But Mike Capp is right: in terms of efficiency, this is a horrible way to do
it.  For a stack, you're better off with a linked list.

~John Demme



More information about the Digitalmars-d mailing list