加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Cocos2d-x Vector——vector iterators incompatible

发布时间:2020-12-14 14:16:14 所属栏目:百科 来源:网络整理
导读:***************************************转载请注明出处: http://blog.csdn.net/lttree ****************************************** 使用 cocos2d-x 中的 Vector的时候, 在删除某个对象的时候出现了个错误,很崩溃啊..... VectorBullet** bullets;// 遍

***************************************转载请注明出处: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方法的遍历,我还没想到要怎么改。。。





******************************************

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读