开发者

Multimaps in C++

I am trying to use multimaps in C++. The main aim is that there is a map that stores the multimap pointer.

Now when I try to insert into the multimap I am getting the problem. Can someone tell me where am I going wrong.

typedef multimap<int,int> mm;
typedef map<int,mm*> v_ma开发者_运维技巧p;

int main()
{
v_map map1;

v_map::iterator it;
it = map1.find(23);

mm *mm_map_pointer;

if( it == map1.end())
  {
   mm m_map1; 
   map1[23] = &m_map1;
   mm_map_pointer = &m_map1;
  }
else
 {
   mm_map_pointer = it->second; 
 }

mm_map_pointer->insert( pair<int, int>(1, 2));
return 0;
}

The problem is with mm_map_pointer->insert( pair(1, 2)); Can someone help?


Your m_map1 is a local variable, and you're trying to store a pointer to that in your map. This results in a dangling pointer when the block containing that variable exits.

You have two ways to solve this:

  • My preferred way is to store the multimap in the map directly (i.e., not using a pointer). As a bonus, this simplifies your code a lot:

    typedef multimap<int, int> mm;
    typedef map<int, mm> v_map;
    
    v_map map1;
    map1[23].insert(make_pair(1, 2));
    

    That's it!

  • Your other option is to use new to create a persistent copy of the multimap. In this case, your map should hold a shared_ptr<multimap<...> > so that you don't have to deallocate the multimap manually.


{
 mm m_map1; 
 map1[23] = &m_map1;
 mm_map_pointer = &m_map1;
} // end of scope

Your problem is that m_map1 goes out of scope and is destroyed, leaving you with a dangling pointer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜