在向量中的向量之间移动指针导致向量迭代器不兼容

时间:2011-09-28 16:57:35

标签: c++ vector iterator

我有std::vector个细胞。每个单元格都有其他std::vector来存储一些指向实体的指针。现在我想根据计算新单元格索引将指针从一个单元格移动到另一个单元格。 但我得到了vector iterators incompatible。我知道这是由push_back无效的迭代器引起的,但我不知道为什么,因为push_back不会使用当前现有的entityIter进行操作。我应该如何修改以下示例以使其工作?

    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是指向其他地方分配的实体的指针类型,我不想删除它,只需在单元格之间移动指针。

(我知道这种方法不是最好的方法 - 将指针重新定位到更高的索引单元会导致重新计算它 - 但这是这个问题的目标)

谢谢

2 个答案:

答案 0 :(得分:2)

entitiesInCurrentCell删除的行有一个错误。通过编写

来纠正它
entityIter = entitiesInCurrentCell.erase(entityIter);

从容器中擦除时,擦除函数返回下一个迭代器,因此您不需要递增迭代器。

答案 1 :(得分:1)

从std :: vector中删除会使迭代器无效。请参阅STL vector::erase因此,在调用erase之后,entityIter无效。检查“while(entityIter!= entitiesInCurrentCell.end())”将永远不会成为现实。

将您的代码更改为:

if(entityNewIndex == cellIndex) 
{
  ++entityIter;
}
else 
{
  m_cells[entityNewIndex].entities.push_back(entity);
  entityIter = entitiesInCurrentCell.erase(entityIter);
}
相关问题