In C++, the index operator for maps will either return a reference to the existing value if the key can be found, or a reference to a new, default-initialized value if one with the given key cannot be found.

In D, an exception is thrown instead when a value with the given key cannot be found, similar to unordered_map::at in C++. So if I want to mimic the same behavior (get or initialize to default), I have to do something like

// Assume bar is some associative array of type Foo[string]
Foo* value = key in bar;
if (value) {
    bar[key] = Foo.init;
    value = &bar[key];
}
This seems sub-optimal, given that in involves three hashes (two lookups and one insertion). Is there a more efficient or cleaner way to do so?

Reply via email to