gpt4 book ai didi

c++ - 删除循环列表时找到的列表中的对象的正确方法是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:56:43 26 4
gpt4 key购买 nike

我有一个 Star 结构列表。这些结构在 std::list 中

我正在双重循环此列表并比较那里的位置以检测碰撞。当发现碰撞时,我将删除质量最低的星。但是,如何在双循环中删除星星,并让循环继续检查更多碰撞?

值得一提的是,第二个循环是反向循环。

代码如下

void UniverseManager::CheckCollisions()
{
std::list<Star>::iterator iStar1;
std::list<Star>::reverse_iterator iStar2;
bool totalbreak = false;

for (iStar1 = mStars.begin(); iStar1 != mStars.end(); iStar1++)
{
for (iStar2 = mStars.rbegin(); iStar2 != mStars.rend(); iStar2++)
{
if (*iStar1 == *iStar2)
break;
Star &star1 = *iStar1;
Star &star2 = *iStar2;

if (CalculateDistance(star1.mLocation, star2.mLocation) < 10)
{
// collision
// get heaviest star
if (star1.mMass > star2.mMass)
{
star1.mMass += star2.mMass;
// I need to delete the star2 and keep looping;
}
else
{
star2.mMass += star1.mMass;
// I need to delete the star1 and keep looping;
}

}
}

}
}

最佳答案

你需要像这样利用删除方法的返回值。

iStar1 = mStars.erase(iStar1);
erase = true;
if (iStar1 == mStars.end())
break; //or handle the end condition

//continue to bottom of loop

if (!erase)
iStar1++; //you will need to move the incrementation of the iterator out of the loop declaration, because you need to make it not increment when an element is erased.

如果您在一个项目被删除时不增加迭代器并检查您是否删除了最后一个元素,那么您应该没问题。

关于c++ - 删除循环列表时找到的列表中的对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com