【发布时间】: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--;
}
}
【问题讨论】:
-
什么是
ProjectionList?std::list?std::vector? -
当向后迭代时,您应该考虑使用 reverse iterators。这种情况下的技巧是
erase()接受并返回iterator而不是reverse_iterator,但那是not hard to work around,例如:for (auto it = ProjectileList.rbegin(); it != ProjectileList.rend(); ) { if (it->position_y < 0) { it = decltype(it){ProjectileList.erase(std::next(it).base())}; } else { it->Draw(window.renderer); it->position_y--; ++it; } }