gpt4 book ai didi

c++ - 关于foreach循环和性能的几个问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:02:15 27 4
gpt4 key购买 nike

下面我有几个与foreach相关的问题,希望有人能回答。我知道大多数人并不关心可能微不足道的差异,但我想了解它们的完整性。

1)有人可以解释一下 Qt 中的 foreach 关键字实际上是如何在幕后工作的吗?我想知道 foreach 是否创建一个新的项目对象指针并在下面的示例中的每次迭代中重新评估 collidingItems(可能很昂贵)

foreach (QGraphicsItem *item, someItem->collidingItems(Qt::IntersectsItemShape) {
// do something with item;
}

因此应该这样输入

QGraphicsItem *item;
QList<QGraphicsItem *> itemList = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (item, itemList) {
// do something with item;
}

我假设不是,因为根据文档,它在进入循环之前获取列表的拷贝。但是,如果我没记错的话,至少有一个 for 语句会评估每次迭代的检查,所以我只想确定一下。

2)第二个问题。由于 foreach 复制了列表,是否可以更改 foreach 中的原始内容,如

QList<QGraphicsItem *> itemList = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemList) {
if (item->type() != QGraphicsItem::UserType)
itemList.removeOne(item);
}
// continue using itemList

3)最后一个问题。预先创建和重用指针(如下所示)或每次在 foreach 循环内定义一个新指针(假设一个大列表)在性能上有什么不同吗?

MyGraphicsItem *myItem;   // a complex subclass of QGraphicsItem
foreach (QGraphicsItem *item, someItem->collidingItems(Qt::IntersectsItemShape)) {
myItem = qgraphicsitem_cast<MyGraphicsItem *>(myItem);
// do something with myItem;
}

谢谢!

最佳答案

  1. 它确实复制了您作为 foreach 的第二个参数传递的列表。在您的例子中,collidingItems 返回的列表将被复制到 foreach 中使用的变量中。
  2. 是的,没关系(见下文)。
  3. 我认为不会有性能差异,因为指针是原始类型。如果它是类类型,并且在循环内声明它,则每次迭代都必须调用其构造函数。

来自文档:

Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop. (If you don't modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.)

关于c++ - 关于foreach循环和性能的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3005408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com