• Create Account

### #ActualCodarki

Posted 20 July 2012 - 12:37 PM

Above solutions should all work.. but if order doesn't matter and extra speed is warranted:
// If order doesn't matter, swap to back and and pop. This wont move the
// elements after current iterator during erase, but the order of elements
// will change.
for (vector<Enemy*>::iterator it = enemyVector.begin(); it != enemyVector.end(); )
{
if ((*it)->getState())
{
delete *it;
// Swap to back and pop, and delete it from there, but don't swap the last element.
if (enemyVector.size() > 1)
std::swap(*it, enemyVector.back());
enemyVector.pop_back();
}
else
{
++it;
}
}



Edit: Disregard that, I'll edit another solution (different from above)
Edit2: there.

### #3Codarki

Posted 20 July 2012 - 12:31 PM

Above solutions should all work.. but if order doesn't matter and extra speed is warranted:
// If order doesn't matter, swap to back and and pop. This wont move the
// elements after current iterator during erase, but the order of elements
// will change.
for (vector<Enemy*>::iterator it = enemyVector.begin(); it != enemyVector.end(); )
{
bool const isLast = enemyVector.size() > 1;
if ((*it)->getState())
{
delete *it;
// Swap to back and pop, and delete it from there, but don't swap the last element.
if (enemyVector.size() > 1)
std::swap(*it, enemyVector.back());
enemyVector.pop_back();
}
else
{
++it;
}
}



Edit: Disregard that, I'll edit another solution (different from above)
Edit2: there.

### #2Codarki

Posted 20 July 2012 - 12:23 PM

Since all you want to do is delete each elements and clear the array, split it to two:
for (auto it = enemyVector.begin(), it_end = enemyVector.end(); it != it_end; ++it)
{
delete *it;
}
enemyVector.clear();


Edit: Disregard that, I'll edit another solution (different from above)

### #1Codarki

Posted 20 July 2012 - 12:21 PM

Since all you want to do is delete each elements and clear the array, split it to two:
for (auto it = enemyVector.begin(), it_end = enemyVector.end(); it != it_end; ++it)
{
delete *it;
}
enemyVector.clear();


PARTNERS