Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

People also ask

How do you view elements on a map?

C++ map at() function is used to access the elements in the map with the given key value. It throws an exception out_of _range, if the accessed key is not present in the map.

Can you use a pointer as a key to a map?

C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.

How do I access pointers?

To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.


You can do this:

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

or

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

or

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

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

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

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