DLang Notes and Examples
← prev | next →     Top-level ToC     /data-structures.html     (printable version)

1 Arrays

Arrays know their length. Array properties: .ptr, .length, and .capacity.

// Static array on the stack.
int[3] a1;  // initialized to [0, 0, 0]
typeid(a1); //=> int[3]
a1.length; //=> 3
a1.capacity; //=> 0, since it's a static array.

// Dynamic array (resizable) on the heap. These are GC'd.
int[] a2;  // empty
a2.length; //=> 0
a2.length = 3; // now it's [0, 0, 0].
typeid(a2); //=> int[]
a2 = new int[5];  // length is now 5, initialized to [0, 0, 0, 0, 0]
int[] a3 = new int[10];  // starts off with length 10.
a3.reserve(20); // increases capacity on this array.

Of course,

auto a = [1, 2, 3];  // gets you a dynamic array.

Capacity is how large the array can get before it needs to reallocate space for itself. So, static arrays always have .capacity = 0 since they don’t re-allocate.

.ptr is the address of the array.

Remember: new gets you a dynamic (on the heap) object.

Append elems to a dynamic array:

int[] a;
a ~= 3; 
a ~= 4;

Concat arrays: a ~ b. Note, auto a = a1 ~ a2 gives you a dynamic array, even if you’re concatting two static arrays. But you can get a static array if you know sizes:

int[5] a = a1 ~ a2;  // if a1.length + a2.length == 5

1.1 Copying an Array

auto a = [1, 2, 3];
auto b = a; // `b` refers to the same array `a` does.
// modifying `b` will also change `a`.
auto c = a.dup; // `c` is a *shallow* copy of `a`.

2 Associative Arrays

Aka “hashes”.

int[string] h;  // a hash of string --> int
h["a"] = 1;
h["b"] = 2;
h["c"] = 3;

writeln(h["b"]); // 2

if ("c" in h) {
    writeln("yes, \"c\" is a key in `h`.");
}