Reputation: 209
i'm initializing and inserting into a list like so
_ARRAY_DETAIL* pAR = new _ARRAY_DETAIL;
pAR->sVar1 = 1;
pAR->nVar2 = 2;
m_SomeList.push_back(pAR);
i am trying to find and erase all from the list that contains the value 1, and then delete the pointer we created with new
, is my example below doing both in a good, correct efficient way?
while(Iter != m_SomeList.end());
{
if((*Iter)->sVar1 == 1)
{
_ARRAY_DETAIL* pAR = *Iter;
Iter = m_SomeList.erase(Iter);
delete pAR; pAR = NULL;
}
Iter++;
}
Upvotes: 2
Views: 576
Reputation: 308206
Once you erase the iterator, it's no longer valid. You need to increment it before the erase.
if((*Iter)->sVar1 == 1)
{
_ARRAY_DETAIL* pAR = *Iter;
m_SomeList.erase(Iter++);
delete pAR;
}
else
++Iter;
You were correct that erase
returns an incremented iterator but I prefer to do it explicitly, before the iterator is erased.
Setting pAR to NULL is redundant, since it's going out of scope on the next line anyway.
Also note that you should only increment Iter
if you didn't increment it in the other part of the if
.
Upvotes: 2
Reputation: 17441
as an alternative you could use remove if
although what you have done seems fine.
bool IsOne (_ARRAY_DETAIL* pAR) {
if(pAR->sVar1 == 1) {
delete pAR;
return true;
}
return false;
}
remove_if (vec.begin(), vec.end(), IsOne);
Upvotes: 1