Cocos2d-x Vector——vector iterators incompatible

***************************************转载请注明出处:http://blog.csdn.net/lttree******************************************



使用 cocos2d-x 中的 Vector的时候,

在删除某个对象的时候出现了个错误,非常崩溃啊.....

Vector<Bullet*>* bullets;


// 遍历每一个bullet,让他们自己更新
for ( auto it = bullets->begin();it!=bullets->end();it++)
{
  (*it)->update();

  // 获取子弹生命。若子弹已经消亡,释放
  if( (*it)->getLife() )	{
			
    Bubblet* b = *it;

    bubblets->eraseObject(b);
    this->removeChild( b,true );
  }
		 
}

就会错误发生——vector iterators incompatible。

也许是我 打开的方式不正确。于是用C++11方法:

Vector<Bullet*> bullets;

for( auto& b : bullets )  {
  b->update();

  if( b->getLife() )  {
    bubblets.eraseObject(b);
    this->removeChild(b,true);
  }

}

还是不行。。。

找了非常久,发现,

据说是由于,迭代器遍历的时候。假设把当前的给删除了,那么后面就乱套了,无法继续进行下去了,

所以。会崩溃。


于是乎。假设通过迭代器来遍历,就这么改:

// 遍历每一个bullet。让他们自己更新
for ( auto it = bullets->begin();it!=bullets->end();)
{
  (*it)->update();

  // 获取子弹生命,若子弹已经消亡,释放
  if( (*it)->getLife() )	{
			
    Bubblet* b = *it;

    it = bubblets->eraseObject(b);
    this->removeChild( b,true );
  }
  else  {
    it++;
  }
		 
}

迭代器的移动,不再靠循环。而是靠推断语句。


可惜。通过C++11方法的遍历,我还没想到要怎么改。。。







***************************************转载请注明出处:http://blog.csdn.net/lttree******************************************

原文地址:https://www.cnblogs.com/wzjhoutai/p/7189590.html