本文介绍了QT的QList是否在容器修改后保存迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在QList中有任何删除操作后,指向QList元素的迭代器是否仍然有效?
我需要从QList中删除一些元素,所以我将这些元素的迭代器存储到另一个容器中,然后使用这个保存的迭代器并使用从QList中删除必要的元素。
看起来像这样:

Are the iterators pointed to elements of QList still valid after there are any remove operation from QList?I need to remove some element from QList, so I store an iterators for those elements to another container and than take this saved iterators and use to remove necessary elements from QList.It looks like this:

// inside a loop for 'list'
QList<type>::iterator it = list.begin() + j;
removing.append(it);
// end of loop for 'list'

...

while(removing.empty() == false)
{
    list.erase(removing.takeFirst());
}

因此,当删除容器包含多个元素,尝试擦除第二个元素时发生应用程序崩溃(SEGMENTATION FAULT),而第一个元素成功擦除。
是什么原因,有没有办法用迭代器删除元素?

So, when removing container contains more than 1 element, app crash occurs (SEGMENTATION FAULT) when attempting to erase second element, whereas first was erased successfully.What is the reason and is there any way to remove elements with iterators?

推荐答案

如果由于某种原因你会以这种方式从容器中删除元素然后你可以尝试使用QLinkedList而不是QList,因为指向QLinkedList中的项的迭代器只要项存在就保持有效,而QList的迭代器可以在插入或删除后变为无效。我从Qt的文档中复制了这个引用:。

If for some reason you would like to remove elements from a container in that way then you could try to use QLinkedList instead of QList because Iterators pointing to an item in a QLinkedList remain valid as long as the item exists, whereas iterators to a QList can become invalid after any insertion or removal. I copied this quotation from Qt's documentation: Container Classes.

这篇关于QT的QList是否在容器修改后保存迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 02:51
查看更多