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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:40:33  来源:igfitidea点击:

Qt foreach loop ordering vs. for loop for QList

c++qtfor-loopforeachqt4

提问by Freedom_Ben

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

当通过迭代QList<T>一个foreach循环,在测试中,我进行了,因为它们与一个标准的项目都以相同的顺序返回for循环。

My question is, will the foreachalways return items in numerical order by index like this, for containers that have natural ordering (like QListand QVector)? For example, are the following alwaysequivalent?

我的问题是,foreach对于具有自然排序(如QListQVector)的容器,是否总是按这样的索引按数字顺序返回项目?例如,以下是否总是等价的?

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 foreachmacro (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 QListor QVectorthen your examples will always be equivalent. You can view the foreachsource code here.

因此,如果您的容器是 a QListorQVector那么您的示例将始终是等效的。您可以在此处查看foreach源代码。

The foreachmacro 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 有一个更好的等价物。

回答by Krozark

Based on the information found here, foreachis much slower than the first, suggesting that it is not equivalent.

根据这里找到的信息,foreach比第一个慢得多,表明它不等价。