After erase in Qmap, the itertator it pointer has been invoked again and will crash. The Erase function returns the address that points to the next data after the deletion.
When using a For loop operation, if the internal use of erase operations, then the it++ operation needs to be placed inside the function body, and erase distinguish.
For example:
Map to 0-9 of the one by one corresponding mapping, to delete the even-numbered items.
#include <QMap>
#include <QDebug>
#include <QtCore/QCoreApplication>
! Test the use of iterator pointers in the for loop in the erase function in the map
! Test Delete Even-numbered items in 0~9
int main (int argc, char *argv[])
{
Qcoreapplication A (argc, argv);
Qmap<int, int> Mapinttoint;
for (int i = 0; i < 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 ();
}
This results in the following output:
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
If the For loop uses the
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;
}
}
Will collapse. Because Mapinttoint.erase (it); After the operation, the IT pointer is freed, the address becomes 0xfeeefeee, and the call to it++ crashes. (0xfeeefeee means that the space the pointer points to has been released by the delete, but the program incorrectly calls this invalid pointer before it is assigned the pointer again)
Therefore, be aware of this when erase operations are performed on Qmap.
In addition, it is advisable to use it = mapinttoint.erase (it) in the form of a erase operation to iterator it, and to prevent it from being invoked again with the same problem.