I have std::vector of cells. Each cell has other std::vector to store some pointers to entities. Now I want to move pointer from one cell to another based on calculation new cell index.
But I am getting vector iterators incompatible. I know that is caused by push_back invalid the iterator, but I do not know why, because push_back doesn’t manipulate with current existing entityIter. How should I modified the following example to make it work?
for(uint32 cellIndex = 0; cellIndex < m_cells.size(); ++cellIndex)
{
std::vector<entity_type> & entitiesInCurrentCell = m_cells[cellIndex].entities;
std::vector<entity_type>::iterator entityIter = entitiesInCurrentCell.begin();
while(entityIter != entitiesInCurrentCell.end())
{
entity_type entity = *entityIter;
uint32 entityNewIndex = calculateIndex(entity->getPosition());
if(entityNewIndex == cellIndex)
{
++entityIter;
continue;
}
m_cells[entityNewIndex].entities.push_back(entity);
entitiesInCurrentCell.erase(entityIter++);
}
}
entity_type is a pointer type which point to entity allocated elsewhere, I do not want to delete it, just move the pointer between cells.
(I know this approach is not the best way – relocating pointer to higher-index cell causes recalculation it – but this is aim of this question)
thank you
The line that erases from
entitiesInCurrentCellhas a bug. Correct it by writingWhen erasing from a container, the next iterator is returned by the erase function, so you do not need to increment the iterator.