Below is a snippet from a trie implementation (the trie is stored in the 1-indexed vector t):
int get(int &u) {
if (!u) {
t.emplace_back();
u = size(t)-1;
}
return u;
}
int insert(string s) {
int u = 1;
for (char c : s) {
u = get(t[u].child[c-'a']);
}
return u;
}
This code is incorrect; can you figure out why?
Answer









A simple fix is to avoid passing a reference into
tacrossemplace_back(). For example, makegettake the child index by value and return the new index:Then the original
u = get(t[u].child[c - 'a']);is safe.This is also wrong: it doesn't update
t[u].child[c-'a']when a node is createdHow about changing
getto take the parent/index instead of the child referenceThen:
This keeps the write-back behavior, while no reference into
tsurvives theemplace_back().