Qt foreach loop ordering vs. for loop for QList
Solution 1
The foreach
macro (aka. Q_FOREACH
) uses the begin()
and end()
iterator request methods of the container.
So if your container is a QList
or QVector
then your examples will always be equivalent. You can view the foreach
source code here.
The foreach
macro isn't great though, it makes a copy of the container - so only use on containers that support implicit-sharing. Use C++11 for( : ) {}
loops if available, otherwise Boost has an equivalent that is superior.
Solution 2
Based on the information found here, foreach
is much slower than the first, suggesting that it is not equivalent.
![Freedom_Ben](https://i.stack.imgur.com/mhRiG.jpg?s=256&g=1)
Freedom_Ben
Updated on August 26, 2020Comments
-
Freedom_Ben almost 4 years
When iterating through a
QList<T>
with aforeach
loop, in the tests I conducted the items are returned in the same order as they are with a standardfor
loop.My question is, will the
foreach
always return items in numerical order by index like this, for containers that have natural ordering (likeQList
andQVector
)? For example, are the following always equivalent?QList<T> list; for( int i=0; i<list.count(); ++i ) { // process items in numerical order by index // do something with "list[i]"; } foreach( T item, list ) { // will items always be processed in numerical order by index? // do something with "item"; }