"C + +" Map Iterator removal example

Source: Internet
Author: User

The map in C + + STL is very common. Usually we traverse in the following way and delete some entry in the map:

map  <int , int ;  Mp;mp.insert ( Make_pair (1 , 1 )); Mp.insert (Make_pair (2 , 3 ); //insert some elements  for  (map  <int , int ; :: Iterator iter = Mp.begin (); Iter! = Mp.end (); iter++) {if  (Iter->first = = 1 ) mp.erase (ITER) ;    //NOTE it is not safe!  else  iter->second++;}  

The above removal is not safe because the structure of ITER has changed since Mp.erase (ITER), and the iter++ of the For loop sheet may be problematic. The following modifications are therefore recommended:

for (map<int, int>::iterator iter = mp.begin(); iter != mp.end(); ) {    if1// NOTE it is SAFE!    else iter->second++;}

The deletion is safe here, because ITER will cache it before it is deleted, and then pass it on to erase to delete it. The iter++ was therefore carried out on the basis of the original ITER. This approach is also recommended in C + + documentation.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"C + +" Map Iterator removal example

Related Article

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.