gpt4 book ai didi

c++ - *迭代器导致段错误

转载 作者:太空狗 更新时间:2023-10-29 20:47:29 24 4
gpt4 key购买 nike

我正在尝试遍历一个列表。以下是一些声明:

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++ - *迭代器导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5528809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com