Pointer to a map
For instance:
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<int, std::string> * mapping = new std::map<int, std::string>();
(*mapping)[1] = "test";
std::cout << (*mapping)[1] <<std::endl;
}
With the introduction of "at" function in c++ 11, you can use mappings->at(key)
instead of (*mapping)[key]
.
Keep in mind that this api will throw out_of_range
exception if the key is not already available in the map.
Not much difference except that you have to use ->
for accessing the map
members. i.e.
mapping->begin() or mapping->end()
If you don't feel comfortable with that then you can assign a reference to that and use it as in the natural way:
map<int, string> &myMap = *mappings; // 'myMap' works as an alias
^^^^^^^^
Use myMap
as you generally use it. i.e.
myMap[2] = "2";
myMap.begin() or myMap.end();
Use the pointer just like you use any other pointer: dereference it to get to the object to which it points.
typedef std::map<int, string>::iterator it_t;
it_t it1 = mappings->begin(); // (1)
it_t it2 = (*mappings).begin(); // (2)
string str = (*mappings)[0]; // (3)
Remember that a->b
is — mostly — equivalent to (*a).b
, then have fun!
(Though this equivalence doesn't hold for access-by-index like (*a)[b]
, for which you may not use the ->
syntax.)