C++ Qt foreach 循环排序与 QList 的 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16825376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt foreach loop ordering vs. for loop for QList
提问by Freedom_Ben
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.
当通过迭代QList<T>
一个foreach
循环,在测试中,我进行了,因为它们与一个标准的项目都以相同的顺序返回for
循环。
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 alwaysequivalent?
我的问题是,foreach
对于具有自然排序(如QList
和QVector
)的容器,是否总是按这样的索引按数字顺序返回项目?例如,以下是否总是等价的?
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";
}
回答by cmannett85
The foreach
macro (aka. Q_FOREACH
) uses the begin()
and end()
iterator request methods of the container.
的foreach
宏(又名。Q_FOREACH
)使用begin()
和end()
迭代器请求该容器的方法。
So if your container is a QList
or QVector
then your examples will always be equivalent. You can view the foreach
source code here.
因此,如果您的容器是 a QList
orQVector
那么您的示例将始终是等效的。您可以在此处查看foreach
源代码。
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.
该foreach
宏也不是很大,虽然,它使容器的副本-所以只能在支持共享隐含的容器使用。for( : ) {}
如果可用,请使用 C++11循环,否则 Boost 有一个更好的等价物。