How to insert key value pairs to new unordered_map* (pointer) in C++?

I have an unordered_map pointer in a structure since I need it in shared memory to access and modify as the program runs.

struct Umaps {std::unordered_map<int, int> *node_index;} ;

I then initialize the unordered_map, node_index, in another function.

Umapsptr->node_index = new std::unordered_map<int, int>();

Where Umapsptr is the pointer to the Umaps structure in my function. I then try to insert values to the unordered_map.

Umapsptr->node_index[5] = 10;

But I get this error and I don’t know how to resolve it:

error: no match for ‘operator=’ (operand types are ‘std::unordered_map<int, int>’ and ‘int’) Umapsptr->node_index[5] = 10;

What am I doing wrong? Any help would be incredibly appreciated.

Answer

Applying [] to a pointer does pointer arithmetic. You want to apply the [] to the pointed at object, so you need to explicitly dereference the pointer:

(*Umapsptr->node_index)[5] = 10;

If you know the key 5 is already in the map, you can use at instead:

Umapsptr->node_index->at(5) = 10;

but this will throw an exception if the key is not present. If you know the key is not present, you can use emplace:

Umapsptr->node_index->emplace(5, 10);

but this will do nothing if the key is already present with a different value.