Debug assertion error - List iterators incompatible

一曲冷凌霜 提交于 2019-12-11 11:57:21

问题


I'm working on a program that is supposed to put every Window in a list, resize it, and move it to a screen position according to a specified layout.

When I'm running this function however I get a debug assertion error saying "list iterators incompatible".

Here is the code:

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

The error occurs during the first for loop, hope someone can help me fix this

Edit:

Here is the getWindowList function:

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

and the windowList definition:

std::list <Window> windowList;

回答1:


Your loop looks like this:

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

Given the above, the issue is this:

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

You're returning a copy of the list, not the original. Thus the iterator to the copy will be used in the loop and not the iterator of windowList. In fact, you are using two different iterators in the loop construct, and neither one of them refers to the original list, only copies.

The fix is to return a reference:

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

You're now returning a reference to the actual list, not a copy. Now the iterators you are using in the loop constraints refer to the same list, not different lists.



来源:https://stackoverflow.com/questions/34842901/debug-assertion-error-list-iterators-incompatible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!