Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we delete before or after erase for an pointer in the vector?

Should we delete before or after erase. My understanding is both are OK. Is it correct?

In addition, is there any case we won't want to delete the element while erasing it? I believe there must be , otherwise, the erase will be happy to take the responsibility.

std::vector<foo*> bar;
...
for (vector<foo*>::iterator itr = bar.begin(); itr != bar.end(); itr++)
{
   delete (*itr);  //before OR
   bar.erase(itr);
   delete (*itr);  //after???
}
like image 427
pierrotlefou Avatar asked Sep 17 '10 06:09

pierrotlefou


1 Answers

"itr" must be used like this;

for (vector<foo*>::iterator itr = bar.begin(); itr != bar.end(); )
{
   delete (*itr);
   itr = bar.erase(itr);
}

However, I'd prefer to first delete all elements, and then clear the vector;

for (vector<foo*>::iterator itr = bar.begin(); itr != bar.end(); ++itr)
   delete (*itr);
bar.clear();
like image 148
Viktor Sehr Avatar answered Oct 05 '22 13:10

Viktor Sehr