本文介绍了Qt foreach循环顺序与QList的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用 code>或 QVector 那么你的例子将永远是等价的。您可以查看 foreach 源代码 here。



宏不是很好不过,它会创建一个容器的副本 - 所以只能在支持隐式共享的容器上使用。 (:){} 循环(如果可用的话),使用C ++ 11 ,否则Boost有一个相当的优越的表示。


When iterating through a QList<T> with a foreach loop, in the tests I conducted the items are returned in the same order as they are with a standard for loop.

My question is, will the foreach always return items in numerical order by index like this, for containers that have natural ordering (like QList and QVector)? 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";
}
解决方案

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.

这篇关于Qt foreach循环顺序与QList的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:50
查看更多