tags:

views:

1027

answers:

3

Simple question but difficult to formulate for a search engine: if I make a pointer to a map object, how do I access and set its elements? The following code does not work.

map<string, int> *myFruit;
myFruit["apple"] = 1;
myFruit["pear"] = 2;
+2  A: 

myFruit is a pointer to a map. If you remove the asterisk, then you'll have a map and your syntax following will work.

Alternatively, you can use the dereferencing operator (*) to access the map using the pointer, but you'll have to create your map first:

map<string, int>* myFruit = new map<string, int>() ;
swongu
This kinda misses the point. He already knows that he cannot access the elements, but he has a pointer, and it's already allocated.
GMan
I re-read the question and I don't see a mention that the map is already allocated -- or did I miss this?
swongu
+2  A: 
map<string, int> *myFruit;
(*myFruit)["apple"] = 1;
(*myFruit)["pear"] = 2;

would work if you need to keep it as a pointer.

Rusky
+11  A: 

You can do this:

(*myFruit)["apple"] = 1;

or

myFruit->operator[]("apple") = 1;

or

map<string, int> &tFruit = *myFruit;
tFruit["apple"] = 1;
Greg Hewgill
Don't forget to allocate the map object with new first.
Matt H
My answers assume that `myFruit` is an already existing pointer to a `map<string, int>` somewhere, which may or may not have been allocated on the heap.
Greg Hewgill