QT类学习系列(9)- Qt::QMap在for循环中使用erase的用法注意

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

}

会崩溃!!!

解释:因为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<T,T>::iterator等等都要注意这个问题;

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值