如何从QList中删除元素,同时使用foreach迭代它?

问题描述:

我是Qt的新手,试图学习习语。

I'm new to Qt and trying to learn the idioms.

foreach 文档说:


Qt在进入foreach循环时自动获取容器的副本。如果你在迭代时修改容器,这不会影响循环。

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.

但它不说如何在使用 foreach 进行迭代时删除元素。我最好的猜测是:

But it doesn't say how to remove an element while iterating with foreach. My best guess is something like:

int idx = 0;
foreach (const Foo &foo, fooList) {
  if (bad(foo)) {
    fooList.removeAt(idx);
  }
  ++idx;
}

看起来很丑陋,必须有 idx 外部循环(并且必须保持一个单独的循环计数器)

Seems ugly to have to scope idx outside the loop (and to have to maintain a separate loop counter at all).

此外,我知道 foreach 生成 QList 的一个副本,它很便宜,但是当我删除一个元素时会发生什么 - 仍然很便宜,昂贵的复制副本正在进行?是的,深度复制发生

Also, I know that foreach makes a copy of the QList, which is cheap, but what happens once I remove an element -- is that still cheap or is there an expensive copy-on-modify going on? Yes, deep copy happens.

编辑:这似乎并不像惯用的Qt。

EDIT : This doesn't seem like idiomatic Qt either.

for (int idx = 0; idx < fooList.size(); ) {
  const Foo &foo = fooList[idx];
  if (bad(foo)) {
    fooList.removeAt(idx);
  }
  else ++idx;
}


你应该更好地使用迭代器:

// Remove all odd numbers from a QList<int> 
QMutableListIterator<int> i(list);
while (i.hasNext()) {
    if (i.next() % 2 != 0)
        i.remove();
}