Skip to content

Zig ArrayHashMap & Sets

The hash map from the last lesson is great at lookups, but it hands you its pairs in a scrambled order. Very often you want the order you put things in: a menu, the columns of a table, settings read from a file. Zig’s array hash map does that. It’s a hash map and an array at the same time, so you get fast lookups by key and the items in a neat row, in insertion order. This lesson also covers the other common trick: using a map as a set.

The array hash maps live in std.array_hash_map. There are two you’ll use: Auto(K, V) for number, enum and plain struct keys, and String(V) for string keys. Here’s a menu:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var menu: std.array_hash_map.String(u32) = .empty;
defer menu.deinit(gpa);
try menu.put(gpa, "soup", 450);
try menu.put(gpa, "salad", 600);
try menu.put(gpa, "pasta", 950);
try menu.put(gpa, "cake", 500);
var it = menu.iterator();
while (it.next()) |entry| {
std.debug.print("{s}: {d} cents\n", .{ entry.key_ptr.*, entry.value_ptr.* });
}
std.debug.print("pasta costs {?d}\n", .{menu.get("pasta")});
}

Output:

soup: 450 cents
salad: 600 cents
pasta: 950 cents
cake: 500 cents
pasta costs 950

Everything you know from the last lesson still works: .empty, deinit(gpa), put(gpa, ...), get returning an optional, getPtr, contains, getOrPut, count. The difference is the order: it comes out exactly as it went in.

Because the pairs sit in arrays, you can get them as slices and use all your slice skills on them. A for loop over both at once is the nicest way to walk an array hash map:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var temps: std.array_hash_map.String(i32) = .empty;
defer temps.deinit(gpa);
try temps.put(gpa, "Mon", 12);
try temps.put(gpa, "Tue", 15);
try temps.put(gpa, "Wed", 9);
for (temps.keys(), temps.values()) |day, t| {
std.debug.print("{s}: {d}\n", .{ day, t });
}
for (temps.values()) |*t| t.* += 1;
std.debug.print("after warming up: {any}\n", .{temps.values()});
std.debug.print("first day: {s}\n", .{temps.keys()[0]});
std.debug.print("Wed is at index {?d}\n", .{temps.getIndex("Wed")});
}

Output:

Mon: 12
Tue: 15
Wed: 9
after warming up: { 13, 16, 10 }
first day: Mon
Wed is at index 2
  • keys() and values() line up: keys()[i] belongs with values()[i].
  • You can change values through values(), like the |*t| loop does.
  • Don’t change keys through keys(). The hash index still thinks each key is where it was, so lookups would break.
  • getIndex(key) tells you a key’s position, or null.

There’s no plain remove on an array hash map. You have to choose, just like with an ArrayList:

const std = @import("std");
fn show(label: []const u8, keys: []const []const u8) void {
std.debug.print("{s}:", .{label});
for (keys) |k| std.debug.print(" {s}", .{k});
std.debug.print("\n", .{});
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var tabs: std.array_hash_map.String(void) = .empty;
defer tabs.deinit(gpa);
for ([_][]const u8{ "home", "mail", "news", "docs", "music" }) |name| {
try tabs.put(gpa, name, {});
}
show("start", tabs.keys());
_ = tabs.orderedRemove("mail");
show("orderedRemove mail", tabs.keys());
_ = tabs.swapRemove("home");
show("swapRemove home", tabs.keys());
}

Output:

start: home mail news docs music
orderedRemove mail: home news docs music
swapRemove home: music news docs
  • orderedRemove keeps the order, but shifts every later entry (and fixes up the index), so it gets slow on big maps.
  • swapRemove is fast, but moves the last entry into the gap: music jumped to the front.

Both return true if the key was there. If keeping the order is the reason you picked an array hash map, use orderedRemove. If you remove a lot from a big map and order doesn’t matter, swapRemove, or maybe a plain hash map is the better fit. (fetchOrderedRemove and fetchSwapRemove also give you the removed key and value.)

That example also sneaked in this lesson’s second topic: String(void), a map with no values. More on that in a moment.

Since the entries live in arrays, you can sort them. sort takes a small struct with a lessThan method that compares two positions (indexes), and it rebuilds the hash index afterwards so lookups keep working:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var scores: std.array_hash_map.String(u32) = .empty;
defer scores.deinit(gpa);
try scores.put(gpa, "Cy", 40);
try scores.put(gpa, "Ana", 75);
try scores.put(gpa, "Bo", 62);
try scores.put(gpa, "Di", 75);
const HighestFirst = struct {
values: []const u32,
pub fn lessThan(ctx: @This(), a: usize, b: usize) bool {
return ctx.values[a] > ctx.values[b];
}
};
scores.sort(HighestFirst{ .values = scores.values() });
for (scores.keys(), scores.values()) |name, score| {
std.debug.print("{s}: {d}\n", .{ name, score });
}
std.debug.print("Bo still found: {?d}\n", .{scores.get("Bo")});
}

Output:

Ana: 75
Di: 75
Bo: 62
Cy: 40
Bo still found: 62

lessThan(a, b) answers “should the entry at a come before the entry at b?” We say yes when its score is higher, which gives highest first. The struct carries the values slice so lessThan can look the scores up. This kind of “struct that carries what the compare function needs” is called a context, and Zig Sorting & Searching explains it properly. sort is stable, so Ana and Di, who tie, keep their original order.

A set is a collection of things where each thing appears at most once, and the main question is “is this in it?”. Zig doesn’t have a separate set type for this. Instead you use a map whose value type is void, the type with no data at all. The value is written {}:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var visited: std.AutoHashMapUnmanaged(u32, void) = .empty;
defer visited.deinit(gpa);
const pages = [_]u32{ 3, 7, 3, 9, 7, 7, 1 };
for (pages) |page| {
try visited.put(gpa, page, {});
}
std.debug.print("{d} different pages\n", .{visited.count()});
std.debug.print("visited 9? {}\n", .{visited.contains(9)});
std.debug.print("visited 4? {}\n", .{visited.contains(4)});
}

Output:

4 different pages
visited 9? true
visited 4? false

Adding a key that’s already there just does nothing new, so duplicates disappear by themselves. contains asks the set question, and remove takes something out. Because void takes zero bytes, the map stores only keys: no memory is wasted on values. The language reference on void shows the same trick, and points out that it’s better than storing a dummy bool or u8, which would cost memory for nothing.

Use a HashMapUnmanaged(T, void) when you only ask “is it in?”, and an array hash map with void when you also want the items in the order they first appeared.

Here’s a job where an array hash map set really shines: drop repeated words but keep the first time each one appeared, in order.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const text = "to be or not to be that is the question";
var seen: std.array_hash_map.String(void) = .empty;
defer seen.deinit(gpa);
var words = std.mem.tokenizeScalar(u8, text, ' ');
while (words.next()) |word| {
try seen.put(gpa, word, {});
}
for (seen.keys()) |word| std.debug.print("[{s}]", .{word});
std.debug.print("\n{d} unique words\n", .{seen.count()});
}

Output:

[to][be][or][not][that][is][the][question]
8 unique words

seen.keys() is the answer, already in first-seen order. With a plain hash map you’d have to keep a separate list to remember the order.

The same “who owns the keys” rule from Zig HashMap applies to array hash maps with string keys: the map stores your slices, not copies. Here every word is a slice of a string literal, so it’s safe.

You want Use
Fast lookups, order doesn’t matter, lots of adding and removing std.AutoHashMapUnmanaged / std.StringHashMapUnmanaged
Lookups and insertion order, or to sort the entries std.array_hash_map.Auto / std.array_hash_map.String
To loop over all entries often, or keys/values as slices std.array_hash_map
A set of things either kind of map with void values
A set of small numbers or enum values a bit set or std.EnumSet (see Zig Other Collections)

The standard library’s own advice, in the doc comment of HashMap: if iterating over the entries is important and needs to be fast, prefer the array hash map. Its doc comment also says it has very little overhead for small maps. Beyond that, measure your own program before worrying about speed.

Make a std.array_hash_map.String(u32) basket. Add bread, milk and eggs with quantities, then add milk again with getOrPutValue so its quantity goes up by 2. Print the basket in the order the items were first added.

Hint: const e = try basket.getOrPutValue(gpa, "milk", 0); e.value_ptr.* += 2; and print with for (basket.keys(), basket.values()).

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var basket: std.array_hash_map.String(u32) = .empty;
defer basket.deinit(gpa);
try basket.put(gpa, "bread", 1);
try basket.put(gpa, "milk", 1);
try basket.put(gpa, "eggs", 6);
const e = try basket.getOrPutValue(gpa, "milk", 0);
e.value_ptr.* += 2;
for (basket.keys(), basket.values()) |item, qty| {
std.debug.print("{d} x {s}\n", .{ qty, item });
}
}

Output:

1 x bread
3 x milk
6 x eggs

milk keeps its original spot because adding to an existing key doesn’t move it.

Given a = { 1, 4, 6, 9 } and b = { 4, 5, 9, 10 }, print the numbers that are in both. Put all of a into a set, then check each number of b.

Hint: std.AutoHashMapUnmanaged(i32, void), put(gpa, n, {}), then if (set.contains(n)).

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const a = [_]i32{ 1, 4, 6, 9 };
const b = [_]i32{ 4, 5, 9, 10 };
var in_a: std.AutoHashMapUnmanaged(i32, void) = .empty;
defer in_a.deinit(gpa);
for (a) |n| try in_a.put(gpa, n, {});
for (b) |n| {
if (in_a.contains(n)) std.debug.print("in both: {d}\n", .{n});
}
}

Output:

in both: 4
in both: 9

This is a set intersection. Checking each number of b is one quick lookup, instead of scanning all of a every time.

Find the first letter in "programming" that appears for the second time, using a set of letters you’ve already seen.

Hint: loop over the bytes. If the set already contains the letter, print it and break; otherwise put it in.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var seen: std.AutoHashMapUnmanaged(u8, void) = .empty;
defer seen.deinit(gpa);
for ("programming") |c| {
if (seen.contains(c)) {
std.debug.print("first repeat: {c}\n", .{c});
break;
}
try seen.put(gpa, c, {});
}
}

Output:

first repeat: r

p, r, o, g are new; the next r is already in the set. For a set of bytes you could also use a 256-bit bit set, which you’ll meet in Zig Other Collections.

  • std.array_hash_map.Auto(K, V) and std.array_hash_map.String(V) are hash maps that keep insertion order.
  • keys() and values() return slices that line up by index. Change values through them, never keys.
  • Remove with orderedRemove (keeps order, slower) or swapRemove (fast, moves the last entry).
  • sort takes a context with lessThan(a_index, b_index) and keeps lookups working.
  • A map with void values is a set: put(gpa, x, {}), contains, remove. It stores only the keys.
  • The old managed std.AutoArrayHashMap is gone since 0.16.

Next up: Zig Sorting & Searching, putting slices in order and finding things fast.

Quick check

1. You put "b", "a", "c" into a std.array_hash_map.String(u8). What does keys() give?
2. How do you write a set of u32 numbers in Zig?
3. You call swapRemove("x") on an array hash map. What happens to the order?
4. Why should you not change keys through map.keys()?