I encountered an erase problem today. I had some doubts before. I decided to make it clear today. First, let's look at the Declaration of the function:
# Include <list>
Iterator erase (iterator LOC );
Iterator erase (iterator start, iterator end );
The erase () function either deletes the element at location Loc, or deletes the elements between start and end (including start but not including end ). the return value is the element after the last element erased.
The last sentence above is hard to understand. In this case, only the source code can be viewed.
The first version of erase (the version that deletes a single element at location LOC) runs in constant time for lists and linear time for vectors, dequeues, and strings. the multiple-element version of erase always
Takes linear time.
The source code is as follows:
Iterator erase (iterator _ position)
{
If (_ Position + 1! = End ())
Copy (_ Position + 1, _ m_finish, _ Position); // first move the following element forward to a unit, overwriting the element to be deleted.
-- _ M_finish;
Destroy (_ m_finish); // release the bucket occupied by the last element
Return _ position; // The position returned here is the next position of the deleted element.
}
Iterator erase (iterator _ first, iterator _ last)
{
Iterator _ I = copy (_ last, _ m_finish, _ First );
Destroy (_ I, _ m_finish );
_ M_finish = _ m_finish-(_ last-_ First );
Return _ first;
}
I think if you read the source code, you will have a good understanding of the working principle of erase. Finally, we will attach a simple test question, which is derived from C ++ primer (the third edition ), I will provide a simple solution.
/*
Please write a program to accept the following definitions
Int Ia [] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
List <int> ilist (IA, Ia + 11 );
Use a single iterator form of erase () to delete all elements with odd positions in ilist
*/
# Include <iostream>
# Include <list>
Using namespace STD;
Int main ()
{
Int Ia [] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
Int ia_size = sizeof (IA)/sizeof (INT );
List <int> ilist (& Ia [0], & Ia [ia_size]);
List <int >:: iterator ite;
For (ITE = ilist. Begin (); ite! = Ilist. End (); ++ ITE)
{
Cout <* ite <"";
}
Cout <Endl;
// Do earse operation
List <int>: iterator tmpite;
Int iindex = 1; // The Position of the record Element
For (ITE = ilist. Begin (); ite! = Ilist. End (); ++ ITE)
{
If (iindex % 2 = 1)
{
ITE = ilist. Erase (ITE); // here ite has expired, so you need to save the returned value
-- Ite; // here -- operation to offset the ++ operation so that all elements can be traversed without missing elements.
}
++ Iindex;
}
For (ITE = ilist. Begin (); ite! = Ilist. End (); ++ ITE)
{
Cout <* ite <"";
}
Cout <Endl;
System ("pause ");
Return 0;
}