QT类学习系列(9)- Qt::QMap在for循环中使用erase的用法注意
QMap中erase后,itertator it指针已经被是否,再次调用将崩溃。erase函数返回指向删除后下一条数据的地址。
若使用for循环进行操作时,若内部使用erase操作,则it++操作需要放到函数体内部,与erase区别开来。
例如:
Map中存入0-9的一一对应的映射,要删除其中的偶数项。
#include #include #include //!测试map中erase函数在for循环中iterator指针的使用方式//!测试删除0~9中的偶数项int main(int argc, char *argv[]){QCoreApplication a(argc, argv);QMap mapIntToInt;for(int i = 0; i < 10; i ++){mapIntToInt.insert(i, i);}QMap::iterator it;QMap::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();}
会崩溃!!!
解释:因为mapIntToInt.erase(it);操作后,it指针被释放,地址变成了0xfeeefeee,再次调用it++ 就会崩溃。(0xfeeefeee的含义为: 指针指向的空间已经被DELETE释放掉,但程序在未给该指针重新赋值前,又错误的调用了这个无效的指针)
因此,对QMap进行erase操作时,要注意这一点。
另外,个人建议,若在erase操作后,还要对给iterator it进行操作时,最好使用it = mapIntToInt.erase(it)的形式,防止再次调用it时,遇到与上面相同的问题。如下:
for (it = mapIntToInt.begin();it != mapIntToInt.end(); ){int num = it.key();qDebug() << "thecurrent number is " << num;if (num % 2 == 0){it = mapIntToInt.erase(it);qDebug() << "erasenumber : " << num;}else{it++;}}
这样,输出结果为:
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
备注:使用QList
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
