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

}

 

這樣,輸出結果爲:

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時,遇到與上面相同的問題。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章