如何从QList中删除元素,同时使用foreach迭代它? [英] How can I remove elements from a QList while iterating over it using foreach?

查看:8523
本文介绍了如何从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;
}


推荐答案

你应该更好地< =http://doc.qt.io/qt-4.8/containers.html#java-style-iterators>使用迭代器:

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

这篇关于如何从QList中删除元素,同时使用foreach迭代它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆