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_map;
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_map1is a local variable, and you’re trying to store a pointer to that in yourmap. 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
multimapin themapdirectly (i.e., not using a pointer). As a bonus, this simplifies your code a lot:That’s it!
Your other option is to use
newto create a persistent copy of themultimap. In this case, yourmapshould hold ashared_ptr<multimap<...> >so that you don’t have to deallocate themultimapmanually.