Vector is very convenient to use and can store any type of data structure. Sometimes we store object pointers in vectors, and so on, when we delete an element, we also need to release the corresponding memory.
This paper mainly discusses the erase method, especially the use of the erase method in the loop body, needing to pay attention to the existence of recessive problem.
There are two types of erase function prototypes:
Iterator Erase (iterator position); iterator Erase (iterator first, iterator last);
For example, there is a Class A,
Class A{public:int ID; A (void); ~a (void);};
Define Vector<a*> VEC
for (int i=0; i<10; i++) {A *p = new A (); P->id = i; Vec.push_back (P);}
The following is to remove the element with ID 5 in VEC:
For (Vector<a*>::iterator Iter=vec.begin (); Iter!=vec.end (); iter++) {if (5 = = (*iter)->id) {Delete * Iter Veci.erase (ITER); }}
At first glance this code is not a problem, in fact there are a lot of problems, when the erase method is called, ITER becomes a wild pointer, continue to loop iter++ error.
Then we continue to modify the code:
For (Vector<a*>::iterator Iter=vec.begin (); Iter!=vec.end (); iter++) {if (5 = = (*iter)->id) {Delete *i ter iter = Veci.erase (ITER); }}
The erase return value is this: an iterator this designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists
Read the above code in fact there is a problem, first of all, the code can not delete two consecutive elements of 5, because after the first deletion, ITER points to the second, after the increment, it points to the second back, and secondly, if the element 5 is at the end of the vector, the deletion of the ITER will also error.
Then the correct wording can be as follows:
For (Vector<a*>::iterator Iter=vec.begin (); Iter!=vec.end ();) {if (5 = = (*iter)->id) {delete *iter; iter = Veci.erase (ITER); } else {iter++; }}
This solves the problem of two consecutive identical elements, and the element to be deleted is at the last, and there is no problem, because after the deletion, Erase returns Vector.end ().
Vector Delete operation Erase method considerations