Correct use of the erase method of STL Map

Source: Internet
Author: User

Correct use of the erase method of STL Map

In the STL map table, an erase method is used to delete the command node from a map.

Eg:

Map <string, string> maptest;

Typedef Map <string, string >:: iterator ITER;

ITER iter = maptest. Find (key );

Maptest. Erase (ITER );

As shown in the preceding figure, only deleting a single node does not cause task problems,

However, when used in a loop, it is often misused because the user does not correctly understand the concept of iterator.

An example like the following is the incorrect syntax,

Eg:

For (ITER iter = maptest. Begin (); iter! = Maptest. End (); ++ ITER)

{

Cout <ITER-> first <":" <ITER-> second <Endl;

Maptest. Erase (ITER );

}

This is a wrong way of writing.ProgramAction unknown. The reason is that map is the associated container. For the associated container, if an element has been deleted, its corresponding iterator will become invalid and should not be used again; otherwise, the program will not be defined.

You can solve this problem using the following methods:

Correct writing

1. Use the previous iterator to locate the next element. Recommended STL usage

For (ITER iter = maptest. Begin (); iter! = Maptest. End ();)

{

Cout <ITER-> first <":" <ITER-> second <Endl;

Maptest. Erase (ITER ++ );

}

2. the erase () member function returns the iterator of the next element.

For (ITER iter = maptest. Begin (); iter! = Maptest. End ();)

{

Cout <ITER-> first <":" <ITER-> second <Endl;

Iter = maptest. Erase (ITER );

}

Original article:

Http://www.cppblog.com/abware/archive/2009/01/22/72459.html

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.