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