Mimicking C++'s indexing behavior in D associative arrays

Matt Kline via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 17 16:21:09 PST 2015


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?


More information about the Digitalmars-d-learn mailing list