I want to dynamically allocate an array of pointers to an unordered_map in C++. The std::unordered map has been typedef as 'dictionary'.
dict_array= ( dictionary **) calloc(input_size, sizeof(dictionary*));
Now I want to access the individual hashmaps, and for each individual hashmap (mydict), I want to access the values using some key. like below:
for (int i=0; i< input_size, i++){
dictionary *mydict= dict_array[i];
mydict[some_key]++; /*access the value against 'some_key' and increment it*/
}
But this above line to access the value against the key generates a compilation error. What would be the correct way to access it?
In your example, you haven't actually allocated any dictionary
or (std::unordered_map
) objects yet.
The dict_array[i]
is simply a null pointer. Thus the assignment to mydict
also results in a null pointer. You would need to construct a dictionary
first by invoking dict_array[i] = new dictionary();
.
The expression mydict[some_key]++
doesn't mean what you think it does because mydict
is a dictionary *
and not a dictionary
. Thus you would need to actually dereference it first before having access to a valid dictionary
object:
(*my_dict)[some_key]++
But again, before this would work, you need to initialize the underlying pointers.
Also, it's generally a bad idea (which often leads to undefined behavior) to mix C allocation with C++ standard objects.