Std::map inside the erase (iterator) call attention to detail

Source: Internet
Author: User

Method One:

[CPP]  View plain copy std::map<std::string, std::string > maptest;   bool  TestVal (const std::string & val);      ......   std::map<std: : String, std::string >::iterator it = maptest.begin ();   while (it !=  maptest.end ())    {            if (TestVal ( It->second))             {                     it =  Maptest.erase (IT);            }             else                     it++;  }   ...........   In this way, through the STD:: The erase method of the map, after releasing it, returns a pointer to the next element to get the latest iterator


Method Two:

[CPP]  View plain copy std::map<std::string, std::string > maptest;   bool  TestVal (const std::string & val);      ......   std::map<std: : String, std::string >::iterator it = maptest.begin ();   while (it !=  maptest.end ())    {            if (TestVal ( It->second))             {                    maptest.erase (it++);             }             else                     it++;  }   ...........   This method utilizes the features of Post + +, This time to execute Maptest.eraSE (it++); This statement is divided into three processes

1. Assign value of it to a temporary variable as a parameter variable passed to erase

2. Because parameter processing takes precedence over function calls, the next step is to perform the it++ operation, where it now points to the next address.

3, and then call the Erase function, release the first step to delete the value of it to remove the temporary variable refers to the location.


If only maptest.erase (it); When this statement is executed, it is an illegal pointer, and if you do it again, it will go wrong.


To sum up, the movement of ITER needs attention when it comes to erase.


from:http://blog.csdn.net/lmh12506/article/details/9167653

Note: I have encountered such a mistake before, but when I see it again, I forget to look at other people's posts.

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.