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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With