【问题标题】:invalid std::vector iterator无效的 std::vector 迭代器
【发布时间】:2017-04-05 03:28:28
【问题描述】:

我开始为我正在使用 C++ 和 sfml 开发的游戏编写自己的粒子效果系统。 在我的更新方法中,我在迭代向量时删除了生命周期已过期的粒子。 正如您在方法底部看到的那样,我想我小心不要在删除元素后使迭代器无效,但我得到了 exec_bad_access 代码=1 或代码=2。 异常总是指向擦除(它)行。 有什么想法可能是错的吗?

void ParticlesNode::updateCurrent(sf::Time dt)
{
   for(particleIterator it = _mParticles.begin(), end = _mParticles.end(); it != end;)
{
    // calculate new color RGBA
    float nr = it->color.r + it->colorDis.r * dt.asSeconds();
    float ng = it->color.g + it->colorDis.g * dt.asSeconds();
    float nb = it->color.b + it->colorDis.b * dt.asSeconds();
    float na = it->color.a + it->colorDis.a * dt.asSeconds();
    it->color = sf::Color{static_cast<Uint8>(nr),static_cast<Uint8>(ng),static_cast<Uint8>(nb),static_cast<Uint8>(na)};

    // new position
    it->pos = sf::Vector2f(it->pos.x + it->vel.x * dt.asSeconds(), it->pos.y + it->vel.y * dt.asSeconds());

    // new velocity by linear accelaration.
    float length = getLength(it->vel);
    float newLength = length + _mPData.accel * dt.asSeconds();
    float radians = cartesianToPolar(it->vel).y;

    it->vel = polarToCartesian(newLength, radians);
    // new velocity by gravity
    // new velocity by radial acceleration.


    // new remaining life time
    it->lifeSpan -= dt.asSeconds();
    if (it->lifeSpan <= 0)
       _mParticles.erase( it );
    else
        ++it;
 }
}

【问题讨论】:

    标签: c++ vector iterator


    【解决方案1】:

    erase 之后,迭代器it 失效,但仍用于下一次迭代。

    你应该通过erase的返回值来分配它,它指的是被擦除元素之后的迭代器。

    it = _mParticles.erase( it );
    

    请注意,不仅erase处的迭代器失效,之后的所有迭代器,包括end()也失效。因此,您需要为每次迭代评估end(),即将for 的条件更改为

    for(particleIterator it = _mParticles.begin(); it != _mParticles.end();)
    

    【讨论】:

    • 谢谢,我尝试了两种方式,分配和不分配,仍然崩溃。
    • 嘿,你的第二个建议奏效了,我没有重新评估结束迭代器,那就是 curlpit。谢谢你帮我理顺!不过有一件事,我认为没有必要分配它 = _mParticles.erase(it);无论如何它都会在那里。再次感谢。
    • @BennyAbramovici 它可能适用于您当前的 STL 库和编译器,但最好不要依赖它;因为标准明确提到了预期的行为。
    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 2011-05-06
    • 2010-09-08
    • 2017-04-15
    • 1970-01-01
    • 2018-01-27
    • 2018-04-27
    • 2012-05-07
    相关资源
    最近更新 更多