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.
A map that remembers order
Section titled “A map that remembers order”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 centssalad: 600 centspasta: 950 centscake: 500 centspasta costs 950Everything 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.
keys() and values() are plain slices
Section titled “keys() and values() are plain slices”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: 12Tue: 15Wed: 9after warming up: { 13, 16, 10 }first day: MonWed is at index 2keys()andvalues()line up:keys()[i]belongs withvalues()[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, ornull.
Removing: swapRemove or orderedRemove
Section titled “Removing: swapRemove or orderedRemove”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 musicorderedRemove mail: home news docs musicswapRemove home: music news docsorderedRemovekeeps the order, but shifts every later entry (and fixes up the index), so it gets slow on big maps.swapRemoveis fast, but moves the last entry into the gap:musicjumped 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.
Sorting a map
Section titled “Sorting a map”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: 75Di: 75Bo: 62Cy: 40Bo still found: 62lessThan(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.
Using a map as a set
Section titled “Using a map as a set”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 pagesvisited 9? truevisited 4? falseAdding 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.
Removing duplicates, keeping the order
Section titled “Removing duplicates, keeping the order”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 wordsseen.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.
Which map should you use?
Section titled “Which map should you use?”| 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.
Practice
Section titled “Practice”1. Shopping basket in order
Section titled “1. Shopping basket in order”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 bread3 x milk6 x eggsmilk keeps its original spot because adding to an existing key doesn’t move it.
2. Numbers in both lists
Section titled “2. Numbers in both lists”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: 4in both: 9This is a set intersection. Checking each number of b is one quick lookup, instead of scanning all of a every time.
3. First repeated letter
Section titled “3. First repeated letter”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: rp, 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)andstd.array_hash_map.String(V)are hash maps that keep insertion order.keys()andvalues()return slices that line up by index. Change values through them, never keys.- Remove with
orderedRemove(keeps order, slower) orswapRemove(fast, moves the last entry). sorttakes a context withlessThan(a_index, b_index)and keeps lookups working.- A map with
voidvalues is a set:put(gpa, x, {}),contains,remove. It stores only the keys. - The old managed
std.AutoArrayHashMapis gone since 0.16.
Next up: Zig Sorting & Searching, putting slices in order and finding things fast.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- std.array_hash_map source (0.17.1): the doc comment on
Customexplains insertion order, removal costs and the small-map trick. - Zig language reference: void: using
voidvalues to turn a map into a set. - Zig 0.16.0 release notes: Migration to Unmanaged Containers: the old managed array hash maps removed and the new names.
- Zig’s HashMap, Part 1: a community article comparing hash maps and array hash maps. Written for an older Zig, so the type names differ.