Qt:在使用foreach宏进行迭代时,是否可以删除QList元素? [英] Qt: is removing QList elements while iterating using foreach macro possible?
问题描述
我是Qt的新手,正在尝试学习习语.
I'm new to Qt and trying to learn the idioms.
当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 Yes, deep copy happens.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?
这也不像是惯用的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();
}
这篇关于Qt:在使用foreach宏进行迭代时,是否可以删除QList元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!