Dynamic Arrays as Stack and/or Queue
mipri
mipri at minimaltype.com
Mon Oct 7 19:38:50 UTC 2019
On Monday, 7 October 2019 at 19:16:31 UTC, IGotD- wrote:
> On Monday, 7 October 2019 at 17:36:09 UTC, Ferhat Kurtulmuş
> wrote:
>>>
>>> I'm not talking about memory deletion. I'm talking about
>>> push, pop, enqueue, and dequeue behavior. I'd assume in a
>>> garbage collected language letting the reference float off
>>> should be picked up by the GC.
>> I'm sorry. Writing on my mobile phone. Maybe this is what you
>> are looking for
>> https://dlang.org/phobos/std_container_dlist.html
>
> I think what he is looking for are the general pop_front,
> push_front, pop_back and push_back that you would find in
> virtually any C++ STL container algorithms like list, vector or
> map.
>
> I think this is a good question as I don't really see any good
> example in the documentation of the dynamic arrays about this.
> This is very common use case for arrays. Is there any D
> equivalent?
With the performance that you'd expect, I believe:
#! /usr/bin/env rdmd
import std.stdio;
import std.algorithm : moveAll;
void push_front(T)(ref T[] xs, T x) {
++xs.length;
moveAll(xs[0 .. $-1], xs[1..$]);
x[0] = x;
}
T pop_front(T)(ref T[] xs) {
T x = xs[0];
moveAll(xs[1 .. $], xs[0 .. $-1]);
--xs.length;
return x;
}
void push_back(T)(ref T[] xs, T x) {
xs ~= x;
}
T pop_back(T)(ref T[] xs) {
T x = xs[$ - 1];
--xs.length;
return x;
}
void main() {
int[] xs;
foreach (i; 0 .. 10)
xs.push_back(i);
writeln(xs.pop_back()); // output: 9
writeln(xs.pop_front()); // output: 0
writeln(xs.pop_front()); // output: 1
writeln(xs); // output: [2, 3, 4, 5, 6, 7, 8]
}
More information about the Digitalmars-d-learn
mailing list