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???
}
"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();
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