[Qt-interest] What is the best, "for" or "foreach"?

Ross Driedger ross at earz.ca
Mon Nov 30 00:59:36 CET 2009


On Sat, 28 Nov 2009 11:35:05 -0500, <qt-interest-request at trolltech.com>  
wrote:

> Or, you can prefer using iterators to walk the list as long as you don't
> need random access. You can write the equivalent loop yourself using
> iterators like this:
> QListIterator<int> iter(list);
> while (iter.hasNext())
> {
>      int value = iter.next();
>      // use value
> }

That's the 'Java' way of doing things.  Qt also implememets iterators  
closer to c++ (what can I say: I love my stl). For the sake of  
completeness:

QList<int> list;
//populate list
for(QList<int>::iterator it = list.begin(); it != list.end(); ++it)
{
     int value = *it;
     // use value
}

There is also a constIterator for when const correctness is important.

I suspect that this, the Java-style version and 'foreach' generate very  
similar, if not identical, object code, so I think what is important is to  
use the style that you are comfotable with.

-- 
"Wagner's music has some wonderful moments but awful half hours. "
Gioacchino Rossini

Ross Driedger
ross_at_earz.ca




More information about the Qt-interest-old mailing list