我想删除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.
答案 0 :(得分:2)
在迭代容器中从容器中删除项目后,迭代器变为无效。试试这个:
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();
}
}