QMap中erase后,itertator it指针已经被是否,再次调用将崩溃。erase函数返回指向删除后下一条数据的地址。
若使用for循环进行操作时,若内部使用erase操作,则it++操作需要放到函数体内部,与erase区别开来。
例如:
Map中存入0-9的一一对应的映射,要删除其中的偶数项。
#include <QMap>
#include <QDebug>
#include <QtCore/QCoreApplication>
//!测试map中erase函数在for循环中iterator指针的使用方式
//!测试删除0~9中的偶数项
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap<int, int> mapIntToInt;
for(int i = 0; i < 10; i ++)
{
mapIntToInt.insert(i, i);
}
QMap<int, int>::iterator it;
QMap<int, int>::iterator ait;
for (it = mapIntToInt.begin();it != mapIntToInt.end(); )
{
int num = it.key();
qDebug() << "thecurrent number is " << num;
if (num % 2 == 0)
{
mapIntToInt.erase(it);
qDebug() << "erasenumber : " << num;
}
else
{
it++;
}
}
system("pause");
return a.exec();
}
这样,输出结果为:
the current numberis 0
erase number : 0
the current numberis 1
the current numberis 2
erase number : 2
the current numberis 3
the current numberis 4
erase number : 4
the current numberis 5
the current numberis 6
erase number : 6
the current numberis 7
the current numberis 8
erase number : 8
the current numberis 9
若for循环中采用
for (it= mapIntToInt.begin();it != mapIntToInt.end(); it++)
{
int num = it.key();
qDebug()<< "the current number is "<< num;
if (num % 2 == 0)
{
mapIntToInt.erase(it);
qDebug()<< "erase number : "<< num;
}
}
将会崩溃。因为mapIntToInt.erase(it);操作后,it指针被释放,地址变成了0xfeeefeee,再次调用it++ 就会崩溃。(0xfeeefeee的含义为: 指针指向的空间已经被DELETE释放掉,但程序在未给该指针重新赋值前,又错误的调用了这个无效的指针)
因此,对QMap进行erase操作时,要注意这一点。
另外,个人建议,若在erase操作后,还要对给iterator it进行操作时,最好使用it = mapIntToInt.erase(it)的形式,防止再次调用it时,遇到与上面相同的问题。