向量迭代器不是增量 .erase() [英] Vector iterator not incremental .erase()

查看:41
本文介绍了向量迭代器不是增量 .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);
    }
}

此代码在CoinSet.erase(i)"之前一直运行良好,我尝试在各个点使用CoinSet.clear()",但无济于事.对此有任何帮助都会很棒,提前致谢!

This code works perfectly well until "CoinSet.erase(i)", I tried using "CoinSet.clear()" at various points, but to no avail. 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;
    }
}

这篇关于向量迭代器不是增量 .erase()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆