About STL Map, pay attention to the usage of erase

Source: Internet
Author: User

Today, in the process of writing a program, the following accident occurred in this situation, I did not find a reason for the moment, very depressed.

#include <iostream> using namespace std;
#include <map>
#include <string>


int main ()
{
Map<int,string> MS;
Ms.insert (Make_pair (1, "Huzhongsan"));
int i=2;
while (i--)
{
Map<int,string>::iterator it = ms.find (i)//here, when I value is 0 o'clock, not found, will return Ms.end ()
Ms.erase (IT), if it is ms.end (), there will be accidents, here will be blocked, blocking the dead, the program will stop here.
}
return 0;
}


How to avoid the above situation, this is good to do, add a judgment on the good, attention, this situation once appeared, if you write is a very large program, there may not be a good one to find out the bug,

And a lot of us (like my rookie), now the internal implementation of the STL map is not very clear, encountered this error, it is difficult to explain, only by guessing, and then programming verification, some

Time really is no reason to speak, hehe

Here's a way to avoid this happening

#include <iostream>
using namespace Std;
#include <map>
#include <string>


int main ()
{
Map<int,string> MS;
Ms.insert (Make_pair (1, "Huzhongsan"));
int i=2;
while (i--)
{
Map<int,string>::iterator it = ms.find (i);
if (It!=ms.end ())//Just so, add a judgment on the OK ...
Ms.erase (IT);
}
return 0;
}


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.