Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting duplicate values in std map

Tags:

c++

map

stl

I have a

map<char,my_class*> mymap;

the contents of which are as below.

mymap[0]=('a', 0x1);
mymap[1]=('b',0x2);
mymap[3]=('c',0x3);
mymap[4]=('d',0x1);

As you see we have same value for keys 'a' and 'd'. i have a for loop to delete the pointers in the map.

for ( it=mymap.begin() ; it != mymap.end(); it++ ){
  delete it->second;
}

It crashes because it is trying to delete 0x1 twice. I tried doing this

for ( it=mymap.begin() ; it != mymap.end(); it++ ){
  if(!it->second){
      delete it->second;
      it->second = NULL;
  }
}

Even this tries to set a pointer to NULL twice which result sin an exception. What is the best way to delete duplicate values as above in a map?

like image 982
ajay bidari Avatar asked Dec 20 '22 12:12

ajay bidari


1 Answers

NPE's answer involving shared_ptr is good. But if you're forced to use real pointers, I'd probably do it like this:

set<my_class*> values;
for (it=mymap.begin(); it != mymap.end(); it++)
{
  // insert.second will be false if the value is already in the set
  if (values.insert(it->second).second)
    delete it->second;
}

// Make sure you do something with mymap to ensure you don't double-delete later!
like image 65
Chowlett Avatar answered Dec 23 '22 02:12

Chowlett