【问题标题】:Error when trying to remove an object from a list while going through it in C++在 C++ 中尝试从列表中删除对象时出错
【发布时间】:2021-08-27 23:27:22
【问题描述】:

您好,我是 C++ 的初学者,我想知道为什么每次从列表中删除对象时,这段代码都会返回 Debug Assertion Failed 错误。

for (auto it = ProjectileList.end(); it != ProjectileList.begin();) {
            --it;
            if (it->position_y < 0) {
                ProjectileList.erase(it);
            }
            else {
                it->Draw(window.renderer);
                it->position_y--;
            }
        }

【问题讨论】:

  • 什么是ProjectionListstd::list? std::vector?
  • 当向后迭代时,您应该考虑使用 reverse iterators。这种情况下的技巧是erase() 接受并返回iterator 而不是reverse_iterator,但那是not hard to work around,例如:for (auto it = ProjectileList.rbegin(); it != ProjectileList.rend(); ) { if (it-&gt;position_y &lt; 0) { it = decltype(it){ProjectileList.erase(std::next(it).base())}; } else { it-&gt;Draw(window.renderer); it-&gt;position_y--; ++it; } }

标签: c++ list for-loop


【解决方案1】:

另一种解决方案是编写两个循环,一个用于擦除,另一个用于绘制。可以使用std::remove_if

#include <algorithm>
//...
// Erase 
auto iter = std::remove_if(ProjectileList.begin(), ProjectileList.end(), 
                          [&] (auto& p) { return p.position_y < 0; });
ProjectileList.erase(iter, ProjectileList.end());

// Now draw the remaining ones. 
for (auto& p : ProjectileList)
{
    p.Draw(window.renderer);
    p.position_y--;
}

【讨论】:

  • 您可能应该在绘图时保留原始代码的向后迭代。你不能用 range-for 循环来做到这一点(不为此目的使用适配器),但你可以使用反向迭代器,例如:for (auto it = ProjectileList.rbegin(); it != ProjectileList.rend(); ++it) { it-&gt;Draw(window.renderer); it-&gt;position_y--; }
【解决方案2】:

您必须将函数erase() 返回的新迭代器分配给it

for (auto it = ProjectileList.end(); it != ProjectileList.begin();) {
    --it;
    if (it->position_y < 0) {
        it = ProjectileList.erase(it); // assign the new iterator
    }
    else {
        it->Draw(window.renderer);
        it->position_y--;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多