Search code examples
c++listdebuggingfor-loopsyntax-error

Debug assertion error - List iterators incompatible


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;

Solution

  • 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.