moving pointer between vectors in vector causes vector iterators incompatible
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 != entitiesInCurrentCe开发者_开发知识库ll.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 entitiesInCurrentCell
has a bug. Correct it by writing
entityIter = entitiesInCurrentCell.erase(entityIter);
When erasing from a container, the next iterator is returned by the erase function, so you do not need to increment the iterator.
Erasing from std::vector invalidates iterators. see STL vector::erase Therefore entityIter is invalid after the call to erase. Alas the check "while(entityIter != entitiesInCurrentCell.end())" will never become true.
change your code to:
if(entityNewIndex == cellIndex)
{
++entityIter;
}
else
{
m_cells[entityNewIndex].entities.push_back(entity);
entityIter = entitiesInCurrentCell.erase(entityIter);
}
精彩评论