Qt在迭代时删除QMultiHash中的项



我想从我的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.

在迭代容器时从容器中删除项后,迭代器将失效。试试这个:

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();
    }
}

相关内容

  • 没有找到相关文章

最新更新