Qt在迭代时从QMultiHash中删除项目

Posted

技术标签:

【中文标题】Qt在迭代时从QMultiHash中删除项目【英文标题】:Qt Delete Items from QMultiHash while Iterating 【发布时间】:2014-05-12 16:39:10 【问题描述】:

我想从我的 QMultiHash 中删除项目。查看文档,我相信我做得对,但它总是在第一次删除后崩溃。我做错了什么?

这是我的代码:

for (QMultiHash<int, Frame*>::iterator i = m_FrameBuffer.begin(); i != m_FrameBuffer.end(); ++i) 
    if ( (frameNumber - i.key()) >= ( 5 ) )  // Delete frames 5 frames old or more
        qDebug() << "DELETE ==> Key:" << i.key() << "Value:" << i.value() << " Difference: " << (frameNumber - i.key());
        int removed = m_FrameBuffer.remove(i.key());
        qDebug() << "Removed this many: " << removed;
    

这是输出:

FRAME COUNT:  1 
FRAME COUNT:  2 
FRAME COUNT:  3 
FRAME COUNT:  4 
FRAME COUNT:  5 
DELETE ==> Key: 2 Value: Frame(0x138a400)  Difference:  5 
Removed this many:  1 
The program has unexpectedly finished.

【问题讨论】:

【参考方案1】:

当您在迭代容器时从容器中移除项目后,您的迭代器将变得无效。试试这个:

QList<int> keys = m_FrameBuffer.keys();
foreach (int key, keys)

    int diff = frameNumber - key;
    if (diff >= 5)
    
        qDebug() << "DELETE ==> Key:" << key 
                 << "Value:" << m_FrameBuffer.value(key) 
                 << "Difference: " << diff;
        int removed = m_FrameBuffer.remove(key);
        qDebug() << "Removed this many: " << removed;
    

您也可以使用QMutableHashIterator

QMutableHashIterator<int, Frame*> it(m_FrameBuffer);
while (it.hasNext())

    it.next();
    int key = it.key();
    int diff = frameNumber - it.key();
    if (diff >= 5)
    
        qDebug() << "Items to be removed:" 
                 << m_FrameBuffer.values(it.key()).size();
        it.remove();
    

【讨论】:

以上是关于Qt在迭代时从QMultiHash中删除项目的主要内容,如果未能解决你的问题,请参考以下文章

迭代时从Python列表中删除项目[重复]

射击时从列表中删除外星人 - 找出循环; '表达式:不能增加结束列表迭代器'

如何在迭代时从地图中删除?

迭代时从 HashSet 中删除元素 [重复]

迭代Java时从数组中删除对象

如何在迭代时从 HashMap 中删除键? [复制]