简体   繁体   English

C++ 向量迭代器不是增量的

[英]C++ vector iterator not incremental

I've been having a headache with this problem.我一直为这个问题头疼。 I've challenged myself to make a CLI space shooter, where you have you spaceship, lasers and meteors to shoot.我已经挑战自己制作 CLI 太空射击游戏,在那里你可以使用宇宙飞船、激光和流星进行射击。 The problem is this: whenever a laser or a meteor reaches the boundaries of our arena, I want to erase from the vector so that it wouldn't cluster it up.问题是这样的:每当激光或流星到达我们竞技场的边界时,我想从向量中擦除,这样它就不会聚集起来。 Here's how my working code looks now:这是我的工作代码现在的样子:

        std::vector<Meteoras>::iterator itMet = meteorai.begin();
        std::vector<Lazeris>::iterator itLaz = lazeriai.begin();
        while (itMet != meteorai.end() || itLaz != lazeriai.end())
        {
            if (itLaz != lazeriai.end())
            {
                if (itLaz->getCoord()->x == j && itLaz->getCoord()->y == i)
                {
                    itLaz->move(); 
                    ++j; 
                    if (itLaz->getCoord()->x >= ILGIS - 1) continue;
                    else std::cout << itLaz->getIcon();
                }
                ++itLaz;
            }
            if (itMet != meteorai.end())
            {
                if (itMet->getCoord()->x - 1 == j && itMet->getCoord()->y == i)
                {
                    itMet->move();
                    ++j;
                    if (itMet->getCoord()->x <= 0) continue;
                    else std::cout << itMet->getIcon();
                }
                ++itMet;
            }
        }

So there are two "continues" in there.所以那里有两个“继续”。 Instead of them I tried placing iterator removals (as in itLaz = lazeriai.erase(itLaz) but that the program seemed to crash during runtime giving the error that I stated before. I tried doing other logical checks but that didn't seem to work either. I would appreciate if someone could explain a proper way of removing a useless object (in this case a meteor/laser) from a vector.而不是他们,我尝试放置迭代器删除(如在itLaz = lazeriai.erase(itLaz)但程序似乎在运行时崩溃,给出了我之前提到的错误。我尝试进行其他逻辑检查,但似乎没有用如果有人能解释从向量中去除无用物体(在这种情况下是流星/激光)的正确方法,我将不胜感激。

The comment about erase() invalidating an iterator is true.关于erase()使迭代器无效的评论是正确的。 The part about needing to restart at the beginning is wrong.一开始需要重启的部分是错误的。 (You could do, but you certainly don't need to.) (你可以这样做,但你当然不需要。)

erase() returns a still-valid iterator which points to the element after the erased item. erase()返回一个仍然有效的迭代器,它指向被擦除项之后的元素。

if( test for erasing )
{
    itLaz = lazeriai.erase(itLaz);
}
else
{
   ++itlaz;
}

You might be able to refactor your code to use std::remove_if() instead.您可以重构代码以使用std::remove_if()代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM