【发布时间】:2011-04-03 09:50:00
【问题描述】:
我正在尝试浏览列表。以下是一些声明:
list<CG1_Edge*> ActiveEdges;
list<CG1_Edge*>::iterator ActiveEdgeIterator;
有时,此代码在第 2 行出现段错误:
for (this->ActiveEdgeIterator = this->ActiveEdges.begin(); this->ActiveEdgeIterator != this->ActiveEdges.end(); ++this->ActiveEdgeIterator) {
CG1_Edge* currentEdge = *this->ActiveEdgeIterator;
if (currentEdge->y_up < y)
this->ActiveEdges.erase(this->ActiveEdgeIterator);
}
这可能导致段错误的常见原因有哪些?
【问题讨论】:
-
只是风格说明:我会用
std::remove_if替换for循环并调整容器大小。来自 STL 的算法隐藏了许多迭代器细节并使代码更具可读性(当我看到for循环时,我只知道这是某种迭代,而当我看到 STL 算法时,我确切地知道它是什么)。跨度> -
Begemoth 的评论应该是公认的答案。根据标准擦除使“所有迭代器和对位置后元素的引用”无效。所以你至少 需要使用rbegin() 和rend()。但是为什么不使用 std::alogirthms!
-
@sehe:不,这是不正确的。
list::erase不会使迭代器无效,除了那些位于已擦除元素处的迭代器。 -
我的错,我错误地引用了 std::vector 的文档
标签: c++ oop iterator c++-standard-library