调试断言错误 - 列表迭代器不兼容

Debug assertion error - List iterators incompatible

我正在开发一个程序,应该将每个 Window 放入列表中,调整它的大小,然后根据指定的布局将它移动到屏幕位置。

当我 运行 这个函数时,我得到一个调试断言错误 "list iterators incompatible"。

代码如下:

void Control::checkForNewWindows()
{
    for (std::list<Window>::iterator i = mainDetector.getWindowList().begin(); i != mainDetector.getWindowList().end(); ++i)
    {
        bool forBreak = false;
        if ((i->getTitle().find("sample_title") != std::string::npos) && (i->getState() == false))
        {
            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 4; x++)
                {
                    if (activeLayout.windowLayout[y][x].getHandle() == 0)
                    {
                        moveWindow(*i, activeLayout.dimensionsLayout[y][x].x, activeLayout.dimensionsLayout[y][x].y, activeLayout.dimensionsLayout[y][x].width,
                            activeLayout.dimensionsLayout[y][x].height);
                        activeLayout.windowLayout[y][x] = *i;
                        activeLayout.windowLayout[y][x].setState(true);
                        forBreak = true;
                    }
                    if (forBreak)
                    {
                        break;
                    }
                }
                if (forBreak)
                {
                    break;
                }
            }
        }
    }
}

第一次for循环时出现错误,希望有人能帮我解决这个问题

编辑:

这里是 getWindowList 函数:

std::list <Window> Detector::getWindowList()
{
    return windowList;
}

和 windowList 定义:

std::list <Window> windowList;

你的循环看起来像这样:

for (std::list<Window>::iterator i = mainDetector.getWindowList().begin(); 
     i != mainDetector.getWindowList().end(); 
     ++i)

综上所述,问题是:

std::list <Window> Detector::getWindowList()
{
    return windowList;
}

您return正在获取列表的副本,而不是原始列表。因此副本的迭代器将在循环中使用,而不是 windowList 的迭代器。事实上,您在循环构造中使用了两个不同的迭代器,它们都没有引用原始列表,仅引用了副本。

修复是return参考:

std::list <Window>& Detector::getWindowList()
{
    return windowList;
}

您现在return引用的是实际列表,而不是副本。现在您在循环约束中使用的迭代器引用相同的列表,而不是不同的列表。