Alex Rivera | Logout

'for' loop vs Qt's 'foreach' in C++

Asked 2009-04-21T04:12:58.620
58

Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition

QList<QString> listofstrings;

Which is better?

foreach(QString str, listofstrings)
{
    //code
}

or

int count = listofstrings.count();
QString str = QString();
for(int i=0;i<count;i++)
{
    str = listofstrings.at(i);
    //Code
}
Edit
Report

1 Answer

0

You might look at the STL's for_each function. I don't know whether it will be faster than the two options you present, but it is more standardized than the Qt foreach and avoids some of the problems that you may run into with a regular for loop (namely out of bounds indexing and difficulties with translating the loop to a different data structure).

answered 2009-04-21T15:09:01.333

Your Answer