其他分享
首页 > 其他分享> > c – *迭代器导致段错误

c – *迭代器导致段错误

作者:互联网

我正试图通过列表.以下是一些声明:

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);
}

是否有任何常见原因可能会导致段错误?

解决方法:

你应该使用类似的东西:

for (this->ActiveEdgeIterator = this->ActiveEdges.begin(); this->ActiveEdgeIterator != this->ActiveEdges.end(); ) {
    CG1_Edge* currentEdge = *this->ActiveEdgeIterator;
    if (currentEdge->y_up < y)
        this->ActiveEdgeIterator = this->ActiveEdges.erase(this->ActiveEdgeIterator);
    else
        ++this->ActiveEdgeIterator;
}

因为erase返回在下一个元素处定位的迭代器.

(注意:将迭代器作为成员看起来很奇怪.)

标签:c,oop,iterator,c-standard-library
来源: https://codeday.me/bug/20190903/1798138.html