【发布时间】:2012-12-03 14:08:54
【问题描述】:
我在这里使用交换和弹出技术:Erasing element in a vector while iterating using swap-and-pop
以下代码导致“向量迭代器不兼容”断言失败。
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 时,一切正常。
为什么我在使用向量时会出现断言失败?
【问题讨论】:
-
这个断言错误在哪一行?
-
@Leonid:
for(auto iter=vec.begin(); iter!=vec.end();) -
这看起来像
auto正在为您生成错误的类型。您是否尝试过拼写类型而不是使用auto?你用的是什么编译器?vec是如何定义的? -
附带说明,
(*iter).与iter->相同。 ;)