Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to get Python's `defaultdict` behavior in C++?

Tags:

c++

python

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?

like image 251
merlin2011 Avatar asked Oct 14 '13 07:10

merlin2011


People also ask

How does Python Defaultdict work?

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.

Is Defaultdict faster than dict?

Finally, using a defaultdict to handle missing keys can be faster than using dict.

Is Defaultdict slower than 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);


1 Answers

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;
}
like image 158
17andLearning Avatar answered Oct 26 '22 21:10

17andLearning