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.