迭代器在指向integer时自动取消引用



我注意到,当else if语句在该代码中执行时,尽管destination没有被取消引用,但它似乎被解释为它所指向的实际值,而不是迭代器。就好像它被自动取消引用了。for循环按预期执行,但当begin()end()迭代器相等时,类似于done的id将设置为truedestinations是整数的集合,对于这个函数是全局的。

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之前停止循环。

在迭代序列时修改序列通常是个坏主意,它可能会导致迭代器无效,从而导致未定义的行为。

对于dequeerase可能会导致所有迭代器失效,包括用于循环的迭代器。

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++书。特别是,您编写的代码是一个解决得很好的问题。请参阅删除习语。

最新更新