当迭代 QList<T>
时与 foreach
循环,在我进行的测试中,项目以与标准 for
相同的顺序返回环形。
我的问题是,foreach
对于具有自然顺序的容器(如 QList
和 QVector
),总是按这样的索引按数字顺序返回项目?例如,以下 always 是否等价?
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";
}
最佳答案
foreach
宏(又名。Q_FOREACH
)使用 begin()
和 end()
迭代器请求容器的方法。
因此,如果您的容器是 QList
或 QVector
,那么您的示例将始终是等效的。可以查看foreach
源码here .
foreach
宏虽然不是很好,但它会复制容器 - 所以只能在支持隐式共享的容器上使用。如果可用,请使用 C++11 for( : ) {}
循环,否则 Boost 具有更好的等效项。
关于c++ - Qt foreach 循环排序与 QList 的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825376/