Search code examples
c++dictionaryinsertion

c++ map element insertion


I want to insert a pointer to object into a map. Is this the right way?

object myobject[10];
....
mymap.insert( std::pair<int,object*>(pktctr, &myobject[pktctr]));

Solution

  • Is this the right way?

    Yes, although it might read better if you used make_pair:

    mymap.insert(std::make_pair(pktctr, &myobject[pktctr]));
    

    or C++11 syntax:

    mymap.insert({pktctr, &myobject[pktctr]});
    

    The only danger is that you must make sure that the pointer is removed, or the map destroyed, before myobject is destroyed (or, at the very least, make sure that the pointer is never used after that). Otherwise, you'll have a dangling pointer and a whole world of bugs waiting to happen.