Qt foreach循环顺序与QList的循环 [英] Qt foreach loop ordering vs. for loop for QList

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

问题描述

当用 foreach 循环迭代 QList< T> 时,在我进行的测试中,按照与循环的标准相同的顺序返回。



我的问题是, foreach 总是按照索引的顺序以数字顺序返回项目,对于容器自然排序(如 QList QVector )?例如,下面的总是等价的吗?

  QList< T>列表; 

(int i = 0; i< list.count(); ++ i)
{
//按索引
/ /用list [i]做一些事情;
}

foreach(T item,list)
{
//将会按索引的数字顺序处理项目吗?
//用item做一些事情;


解决方案 foreach 宏(aka。 Q_FOREACH )使用 begin()和<$ c

所以如果你的容器是一个 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的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆