ArrayList
std.ArrayList stores a list of elements in an array, allocating memory using an allocator as the list grows:
const std = @import("std");
const expect = std.testing.expect;
test "ArrayList basics" {
const allocator = std.testing.allocator;
var list = std.ArrayList(u64).empty;
defer list.deinit(allocator);
for (0..3) |i|
try list.append(allocator, i);
// 'items' is a slice that points to the elements.
try expect(list.items.len == 3);
try expect(list.items[0] == 0);
try expect(list.items[1] == 1);
try expect(list.items[2] == 2);
}
test "adding elements without initializing them" {
const allocator = std.testing.allocator;
var list = std.ArrayList(u64).empty;
defer list.deinit(allocator);
// addOne adds an element and returns a pointer.
const ptr = try list.addOne(allocator);
ptr.* = 0;
try expect(list.items.len == 1);
try expect(list.items[0] == 0);
// addManyAsSlice adds multiple elements.
const slice = try list.addManyAsSlice(allocator, 3);
slice[0] = 1;
slice[1] = 2;
slice[2] = 3;
try expect(list.items.len == 4);
try expect(list.items[3] == 3);
}
test "using an ArrayList as a stack" {
const allocator = std.testing.allocator;
var stack = std.ArrayList(u64).empty;
defer stack.deinit(allocator);
try stack.append(allocator, 1);
try stack.append(allocator, 2);
try stack.append(allocator, 3);
try expect(stack.getLast() == 3);
try expect(stack.pop() == 3);
try expect(stack.pop() == 2);
try expect(stack.pop() == 1);
try expect(stack.pop() == null);
try expect(stack.getLastOrNull() == null);
}
test "ArrayList capacity" {
const allocator = std.testing.allocator;
// If you know the number of elements in advance,
// it’s more efficient to create the ArrayList with
// an initial capacity.
var list =
try std.ArrayList(u64)
.initCapacity(allocator, 3);
defer list.deinit(allocator);
try expect(list.items.len == 0);
try expect(list.capacity == 3);
for (0..3) |i|
try list.append(allocator, i);
try expect(list.items.len == 3);
try expect(list.capacity == 3);
try list.append(allocator, 3);
try expect(list.items.len == 4);
try expect(list.capacity > 3);
}$ zig test arraylist.zig
All 4 tests passed.
Next example: AutoHashMap.