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 themap
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 themultimap
. In this case, yourmap
should hold ashared_ptr<multimap<...> >
so that you don't have to deallocate themultimap
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.
精彩评论