Reputation:
If I define a pointer-to-map
like this:
map<int, string>* mappings;
mappings
is a pointer. How should I use this pointer to operate the map?
Upvotes: 21
Views: 40627
Reputation: 448
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.
Upvotes: 2
Reputation: 755
Well, STL is designed to reduce the complexity of pointer handling..so better approach is to use stl::iterator.. try to avoid pointers :-/
Upvotes: -3
Reputation: 18218
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;
}
Upvotes: 3
Reputation: 69988
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();
Upvotes: 5
Reputation: 58
another nice way of using pointers, which I like is calling mappings->(and the function you want to call)
Upvotes: 0
Reputation: 385106
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.)
Upvotes: 24