In Python, there is a class called defaultdict
which is essentially a dictionary that will construct elements on demand according to a function specified by the user at construction time..
Does a similar class already exists in C++, or would I have to create it myself by inheriting from map
and overwriting the at
method?
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
Finally, using a defaultdict to handle missing keys can be faster than using dict.
It depends on the data; setdefault is faster and simpler with small data sets; defaultdict is faster for larger data sets with more homogenous key sets (ie, how short the dict is after adding elements);
This is not directly an answer to your question, but if you want the same behavior as defaultdict
for aggregation, you could use map.emplace
to assign a default value if the key does not exist, and return an iterator to the new or existing item (which avoids a second lookup):
unordered_map<int, size_t> map = {{1, 1}, {2, 3}};
// later...
for (int i = 1; i < 4; i++) {
auto emplace_pair = map.emplace(i, 0);
emplace_pair.first->second += 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With