Today in the development process encountered problems, want to traverse a list of nodes, meet certain conditions to delete the node, but because the use of the iterator will appear errors, and finally find a solution, and wrote a test program, hehe:
ListTest.cpp:Defines the entry point for the console application.
#include "stdafx.h" #include <iostream> #include <list> #include <algorithm> using namespace std;
struct St_user {int id;
Char name[255];
};
int _tmain (int argc, _tchar* argv[]) {St_user a1,a2,a3;
A1.id = 1;
sprintf (A1.name, "%s", "xxxxxxxxx");
A2.id = 2;
sprintf (A2.name, "%s", "FFF");
A3.id = 3;
sprintf (A3.name, "%s", "bbbb");
List<st_user*> List1;
List1.push_back (&A1);
List1.push_back (&A2);
List1.push_back (&A3);
printf ("------------------------------\ n"); for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter) {printf ("%s \", *iter)->nam
e);
printf ("------------------------------\ n");
for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end ();)
{if ((*t)->id = = 2) {iter = List1.erase (t);
else ++iter;
printf ("------------------------------\ n"); for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter) {printf ("%s \ n", (*iter)->name);
printf ("------------------------------\ n");
System ("pause");
return 0;
}
Run Result:
--------------------------------------
@2015-7-20 10:06:01 fixed the errors mentioned by netizens, haha, this error is too low, please forgive
The original error code:
for (List<st_user*>::iterator iter = List1.begin (); Iter!= list1.end (); ++iter)
{
if ((*t)->id = = 2)
{
list1.erase (t);
}