简体   繁体   English

向量迭代器不是增量.erase()

[英]Vector iterator not incremental .erase()

I am trying to delete any element of this vector that collides with player. 我正在尝试删除此向量中与玩家发生冲突的任何元素。 However when I try to remove the element from the vector the program crashes and I get the error; 但是,当我尝试从向量中删除元素时,程序崩溃,并且出现了错误; "vector iterator not incremental". “向量迭代器不增量”。

for (std::vector<Coin>::iterator i=CoinSet.begin(); i!=CoinSet.end(); i++) 
{
    if (i->PlayerClear(player.collider()) == true)
    {
        score++;
        cout<<score<<endl;
        CoinSet.erase(i);
    }
}

This code works perfectly well until "CoinSet.erase(i)", I tried using "CoinSet.clear()" at various points, but to no avail. 直到“ CoinSet.erase(i)”为止,这段代码都运行良好,我尝试在各个点使用“ CoinSet.clear()”,但无济于事。 Any help on this would be great, thanks in advance! 在这方面的任何帮助将是巨大的,谢谢!

This has been discussed to death. 已经讨论到死了。 You mustn't operate on an invalid iterator. 您不得对无效的迭代器进行操作。 You want something like this: 您想要这样的东西:

for (auto it = CoinSet.begin(); it != CoinSet.end(); /* no increment here! */ )
{
    if (/* ... */)
    {
        // ...
        CoinSet.erase(it++);
    }
    else
    {
        ++it;
    }
}

I don't like putting ++-statements inside the argument. 我不喜欢将++语句放入参数中。 Therefore erase() returns an iterator that points to the next element, so one could replace the erase line with: 因此,delete()返回一个指向下一个元素的迭代器,因此可以将擦除行替换为:

it = CoinSet.erase(it); // iterator is replaced with valid one

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

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