STL Program Design Practice 2: Pay attention to the failure of iterative
Iterative is a very important feature in STL, but it is very fragile (I personally think) because it is very harsh, and it is not careful. It may be invalid in both mid situations.
1. When the container is inserted
After initializing the iteration, if the container is inserted, iterative may fail.
#include
#include
Using namespace std;
void main ()
{
Vector
Vector
Vecobj.insert (item, 6);
For (; it! = vecobj.end (); iter )
{
Cout << * iter << Endl;
}
}
When compiling and executes the program, the result of the output is messy. This is because the container has occurred while initiating iteration. Therefore, the container needs to be reinitialized after the insertion operation occurs. By replacing the above For statement to the following, you can output it, of course, it is impossible to be so simple in the actual application, but must be careful.
For (iter = vecobj.begin (); it! = vecobj.end (); iter )
2. When the container has deleted elements
After initializing the iteration, if the container has a delete element operation, the iterative may be invalid.
#pragma Warning (Disable: 4786)
#include
#include
Using namespace std;
Int main (void)
{
Vector
Vector
For (; it! = nVec.end (); it )
{
IF (* it == 7) NVEC.RASE (IT);
}
For (it = nVec.begin (); it! = nVec.end (); it )
{
Cout << * IT << Endl;
}
Return 0;
}
Our intent is obviously to delete objects in all containers. But the result is not deleted (don't tell me please use clear).
When we use iteration to delete and insert an element, it is possible to fail. The failure of the iteration may cause many problems, so we have to pay attention. Be careful to use iteration, be careful. Be careful in this world, nothing should be careful, isn't it? :)
The rush of the article, there is a typison or error, please pay more. Thank you for your trip, I am grateful, welcome to communicate with you (- Yuan Kai -).