容器的遍历删除,很多新手都很容易出现bug。
记录,以便自己查找:
QMap<int, int> mapTest{{1, 1}, {2, 2}, {3, 3}, {4, 4}};
//Java风格
QMutableMapIterator<int, int> it(mapTest); //QMapIterator为只读的,所以用QMutableMapIterator
while (it.hasNext())
{
auto element = it.next();
if(element.value() % 2 == 0)
{
continue;
}
it.remove();
}
//STL风格
for(auto mapIt = mapTest.begin(); mapIt != mapTest.end();)
{
if(mapIt.key() % 2 != 0)
{
mapIt++;
continue;
}
mapTest.erase(mapIt++); //mapIt传给函数并自增
}