Ganesh
Ganesh

Reputation: 71

Want to declare pointer to map

How can I declare a pointer to map, how can I insert element into this map and how can I iterate through the elements of this map?

Upvotes: 1

Views: 6523

Answers (2)

Martin Stone
Martin Stone

Reputation: 13007

#include <map>
#include <iostream>

int main() {
    typedef std::map<int, int> IntMap;

    IntMap map;
    IntMap* pmap = &map;

    (*pmap)[123] = 456;
    // or
    pmap->insert(std::make_pair(777, 888));

    for (IntMap::iterator i=pmap->begin(); i!=pmap->end(); ++i) {
        std::cout << i->first << "=" << i->second << std::endl;
    }

    return 0;
}

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

Declaring a pointer to map is a really suspicious desire. Anyway, it would be done like this

#include <map>

typedef std::map<KeyType, ValueType> myMap;
myMap* p = new myMap();
p->insert(std::make_pair(key1, value1));
...
p->insert(std::make_pair(keyn, valuen));

//to iterate
for(myMap::iterator it = p->begin(); it!=p->end(); ++it)
{
   ...
}

Again, a pointer to a map is a horrible option. In any case, google for std::map

Upvotes: 6

Related Questions