我注意到,当else if
语句在该代码中执行时,尽管destination
没有被取消引用,但它似乎被解释为它所指向的实际值,而不是迭代器。就好像它被自动取消引用了。for
循环按预期执行,但当begin()
和end()
迭代器相等时,类似于done
的id将设置为true
。destinations
是整数的集合,对于这个函数是全局的。
void removeDestination(int destinationFloor)
{
bool done = false;
while(!done && !destinations.empty())
{
for (auto destination = destinations.begin(); destination != destinations.end(); ++destination)
{
if(*destination == destinationFloor)
{
destinations.erase(destination);
break;
}
else if(destination == destinations.end())
{
done = true;
}
}
}
}
谢谢你的帮助。
问题与destination
被错误地取消引用无关。else if
分支从未被占用:
else if(destination == destinations.end())
因为如果destination
到达destinations
的末尾,则循环条件:
for (auto destination = destinations.begin(); destination != destinations.end(); ++destination)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
在可以进入CCD_ 13之前停止循环。
在迭代序列时修改序列通常是个坏主意,它可能会导致迭代器无效,从而导致未定义的行为。
对于deque
,erase
可能会导致所有迭代器失效,包括用于循环的迭代器。
Edit:正如评论中所指出的,您已经开发了一种处理无效迭代器的策略。它的效率不是很高,但应该有效。您的问题在于没有正确设置done
变量。
这里的关键是要意识到,如果你已经执行了整个for
循环而没有中断,那么你就完成了。所以你假设你已经完成了,除非你突破了for
循环。
bool done = false;
while(!done && !destinations.empty())
{
done = true;
for (auto destination = destinations.begin(); destination != destinations.end(); ++destination)
{
if(*destination == destinationFloor)
{
destinations.erase(destination);
done = false;
break;
}
}
}
我注意到,当else-if语句在这个代码目标中执行时,尽管没有被取消引用,但似乎被解释为它所指向的实际值,而不是迭代器。
没有。if(*destination == destinationFloor)
将迭代器指向的值与destinationFloor
进行比较。而if(destination == destinations.end())
比较两个迭代器。
destination是一组整数,对于该函数是全局的。
全局变量?不使用标准算法?我鼓励你看一本现代C++书。特别是,您编写的代码是一个解决得很好的问题。请参阅删除习语。