user123003
user123003

Reputation:

How to access elements of a C++ map from a pointer?

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;

Upvotes: 35

Views: 50371

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 992847

You can do this:

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

or

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

or

map<string, int> &tFruit = *myFruit;
tFruit["apple"] = 1;

or (C++ 11)

myFruit->at("apple") = 1;

Upvotes: 87

rpjohnst
rpjohnst

Reputation: 1632

map<string, int> *myFruit;
(*myFruit)["apple"] = 1;
(*myFruit)["pear"] = 2;

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

Upvotes: 3

swongu
swongu

Reputation: 2299

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>() ;

Upvotes: 6

Related Questions