How to delete the element when C ++ STL traverses the map

Source: Internet
Author: User

When we use the erase (iterator it) method of map to delete elements, if erase is in the Code for traversing the map, we need to be careful when calling erase. Erase will invalidate the input parameter iterator and affect the subsequent it ++ logic for traversing the map.

The simple method is to save the it to be deleted, point it used to traverse the map to the next location, and delete the saved it. As shown in the following code:

# Include <map>
# Include <iostream>
Using namespace STD;

Int main ()
{
Map <int, int> map1;
Map <int, int >:: iterator mapit;
Map <int, int >:: iterator saveit;

Map1 [1] = 2;
Map1 [2] = 3;
Map1 [3] = 4;
Map1 [4] = 5;

Mapit = map1.begin ();
While (mapit! = Map1.end ()){
Cout <"element key:" <mapit-> first <", value:" <mapit-> second <Endl;
If (mapit-> first = 2 ){
Saveit = mapit;
Mapit ++;
Map1.erase (saveit );
Continue;
}
Mapit ++;
}

Cout <"map size:" <map1.size () <Endl;
Return 0;
}

 

Note that Windows STL (STL in Windows C ++ compiler) is different from Linux STL (STL in GCC.

In Windows STL, the erase method of map will return an iterator, which points to the iterator after the currently deleted iterator, so in this case, you only need to assign the iterator used for loop to the return value of the erase function. Refer to the above Code as follows:

Mapit = map1.erase (mapit); then you can continue.

However, writing code in Linux cannot be compiled.

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.