开发者

Want to declare pointer to map

开发者 https://www.devze.com 2023-02-13 22:37 出处:网络
How can I decl开发者_StackOverfloware a pointer to map, how can I insert element into this map and how can I iterate through the elements of this map?Declaring a pointer to map is a really suspicious

How can I decl开发者_StackOverfloware a pointer to map, how can I insert element into this map and how can I iterate through the elements of this 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号