Is it safe to delete from an AutoHashMap while looping over it?

Hi there. Zig newbie here.
Can I remove elements from an AutoHashMap while I loop over it without messing up the iteration?

Hi @brodo
welcome to ziggit :slight_smile:

From: std.HashMap

any modification invalidates live iterators

See: ArrayHashMap

Modifying the hash map while iterating is allowed

4 Likes

If you have a reason to keep using the HashMap instead of switching to ArrayHashMap, you could collect the keys in an ArrayList and only remove them afterwards. (If that is possible for your use case / without causing worse performance for your algorithm)

2 Likes

@dimdin , @Sze Thanks a lot! Switching to ArrayHashMap will work just fine for me.

2 Likes

From looking at HashMap source code remove only changes data about removed item and updates size. So it should be safe to iterate over it while removing items from it. But it’s not part of api guaranties so it can change anytime.

Hmm, looks like pointer stability safety for std.HashMap was not integrated with iteration. That would be a nice touch that would make the answer to this question more discoverable because then when someone tries it they will get a safety check failure instead of strange behavior, or worse, seemingly OK behavior that breaks later.

6 Likes