简体   繁体   中英

Want to declare pointer to map

如何声明指向地图的指针,如何将元素插入此地图,以及如何遍历此地图的元素?

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

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM