How STL containers Delete elements in cyclic Traversal

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.