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.
C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With