In actual application, you will encounter a scenario where you need to traverse elements in the container and clear an element from the container after judging certain conditions:
# Include <stdio. h> # include <map> # include <set> # include <list> # include <vector> # include <deque> template <class T> void del (t, int POS) {// delete operation int I = 0 in the Test Loop traversal; For (typename T: iterator it = T. begin (); it! = T. end (); ++ I) {printf ("% d", * It); if (I = POS) {T. erase (it ++);} else ++ it;} printf ("\ n");} int main () {STD: Map <int, int> MP; STD: Set <int> st; STD: List <int> lt; STD: vector <int> VEC; STD: deque <int> dque; for (INT I = 0; I <10; ++ I) {MP. insert (STD: make_pair (I, I); ST. insert (I); lt. push_back (I); Vec. push_back (I); dque. push_back (I);} del (MP, 5); del (St, 5); del (LT, 5); del (VEC, 5); del (dque, 5); Return 0 ;}
Note thatCode, It ++ or ++ it does not occur in the for loop header, but in the for loop body. To delete it, you should use
T. Erase (it ++ );
It ++ this overload operation will move it back and return the current iteration position.
After running the above Code, MAP, set, and list outputs the value correctly. When running to VEC or dque, the asserted crash occurs because after erase is executed, it is invalid, causing the value to fail in the next loop.
Therefore, you must note that the above method of deleting elements in loop traversal does not affect the method of continuing traversal.Relational containers (MAP, list, set, etc.), while linear containers (vector, deque, etc)The problem may occur.