C++ &引用;向量迭代器不兼容“;在使用swap和pop进行迭代时擦除向量中的元素时,断言失败

C++ &引用;向量迭代器不兼容“;在使用swap和pop进行迭代时擦除向量中的元素时,断言失败,c++,vector,C++,Vector,我在这里使用交换和弹出技术: 下面的代码导致“向量迭代器不兼容”断言失败 for(auto iter=vec.begin(); iter!=vec.end();) { if((*iter).isAlive())//update the entity if the entity is alive { (*iter).update(); ++iter; } else //otherwise, get rid of it {

我在这里使用交换和弹出技术:

下面的代码导致“向量迭代器不兼容”断言失败

for(auto iter=vec.begin(); iter!=vec.end();)
{
    if((*iter).isAlive())//update the entity if the entity is alive
    {
        (*iter).update();
        ++iter;
    }
    else  //otherwise, get rid of it
    {
        std::swap(*iter, vec.back());
        vec.pop_back();
    }
}
但是,当我使用std::list而不是std::vector时,它运行良好


为什么使用向量时断言失败?

在最后一个元素上调用
vec.pop_back()
时,
iter
无效,因为它指向
vec.back()
。STL文档说明
vector::pop_back()
使
back()
end()
无效

解决此问题的一种方法是检测
size()==1的特殊情况:

for(auto iter=vec.begin(); iter!=vec.end(); )
{
    if((*iter).isAlive())//update the entity if the entity is alive
    {
        (*iter).update();
        ++iter;
    }
    else if(vec.size() > 1) // can swap&pop
    {
        std::swap(*iter, vec.back());
        vec.pop_back();
    }
    else // need to reset iterator
    {
        vec.pop_back();
        iter = vec.begin();
    }
}
假设:

  • auto
    正在推断正确的类型
  • 循环不变量
    iter=未缓存vec.end()

此断言错误发生在哪一行?@Leonid:
for(auto iter=vec.begin();iter!=vec.end();)
这看起来像是
auto
为您生成了错误的类型。您是否尝试过拼写类型而不是使用
auto
?你在用什么编译器?
vec
是如何定义的?在旁注中,
(*iter)。
iter->
相同。)