0

Following is the code sample taken from Qt application. I want to write following "foreach" loop as for loop with C++ iterators.

DocumentWindow *MdiWindow::activeDocument()
{
  return qobject_cast<DocumentWindow*>(workspace->activeWindow());
}

int i=1;
foreach( QWidget *w, workspace->windowList() ) // workspace = new QWorkspace();
      {
        QString text;
        if( i<10 )
          text = tr("&%1 %2").arg( i++ ).arg( w->windowTitle() );
        else
          text = w->windowTitle();

        QAction *action = windowMenu->addAction( text );
        action->setCheckable( true );
        action->setChecked( w == activeDocument() );
        connect( action, SIGNAL(triggered()), mapper, SLOT(map()) ); // mapper = new QSignalMapper( this );
        mapper->setMapping( action, w );
}

Following is my attempt. It compiles fine, but as soon as this code gets called in a running application it crashes. and I do not know why. Am I doing it right?

DocumentWindow *MdiWindow::activeDocument()
{
  return qobject_cast<DocumentWindow*>(workspace->activeWindow());
}

int i = 1;    
for(QWidgetList::iterator it = (workspace->windowList()).begin(); it != (workspace->windowList()).end(); ++it)
{
            QString text;
            if(i < 10)
                text = QString("&%1 %2").arg(i++).arg((*it)->windowTitle());
            else
                text = (*it)->windowTitle();

            QAction *action = windowMenu->addAction(text);
            action->setCheckable(true);
            action->setChecked((*it) == activeDocument());
            connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
            mapper->setMapping(action, (*it));
}

Answer: I did not realize that workspace->windowList() returns by value and hence both iterators are pointing to different instances of the containers.

nik
  • 8,387
  • 13
  • 36
  • 44

1 Answers1

5

You are calling workspace->windowList() multiple times in the query which would be returning different containers and thus the iterator is not from the same collection.

Store the results of workspace->windowList() in a local variable and iterate over that.

QWigetList winList = workspace->windowList() for(QWidgetList::iterator it = winList.begin(); it != winList.end(); ++it)

The reason this occurs is that the windowList() returns a QWidgetList by value not by reference. See this question for a discussion on what is happening.

Community
  • 1
  • 1
JProgrammer
  • 2,750
  • 2
  • 25
  • 36