1

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?

2
  • You are you creating pointers to standard containers? Commented May 7, 2015 at 17:15
  • Why are you using calloc? And any mention of "dynamic arrays" in C++ will lead to the obligatory "why are you not using std::vector"? Commented May 7, 2015 at 17:17

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Why on earth are you messing around with pointers like this?

If you really want an array of pointers, then you'll have to dereference to access the map itself:

(*my_dict)[some_key]++;

assuming you've correctly set up each pointer to point to a valid dictionary.

Or use a less insane data structure

std::vector<dictionary> dict_array(input_size);

dict_array[i][some_key]++;

Comments

0

use operator[]():

mydict->operator[](some_key)++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.