I recently read the book C ++ primer. In the container chapter, I have a preliminary understanding of the container, and I mentioned the old problem of Joseph Ring in some interviews, A common idea is to use a circular linked list or array.
Here, the trainer decides to use the vector sequence container for implementation:
# Include <vector> <br/> # include <iostream> <br/> using namespace STD; </P> <p> const int n = 1; <br/> const int M = 1; <br/> int main (INT argc, char * argv []) <br/>{< br/> vector <int> ring; <br/> // initialize <br/> for (INT I = 0; I <N; I ++) <br/> ring. push_back (I + 1); </P> <p> vector <int>: iterator ibegin = ring. begin (); <br/> vector <int>: iterator iend; <br/> while (! Ring. empty () <br/>{< br/> iend = ring. end (); <br/> If (ibegin = iend) <br/> ibegin = ring. begin (); </P> <p> for (INT I = 1; I <m; I ++) <br/>{< br/> ibegin ++; <br/> If (ibegin> = iend) <br/> ibegin = ring. begin (); <br/>}< br/> cout <* ibegin <Endl; <br/> ibegin = ring. erase (ibegin); <br/>}< br/>}
During the process, the iterator is not very familiar with the problem:
"Vector iterators incompatible"
Find the cause on the network and summarize it as follows:
Vector can implement erase in any way. It is not guaranteed that after an element of erase, subsequent elements must be moved to the location referenced by this iterator (address ). Of course, this is true in almost all STL implementations, which is why there is no problem after compiling with vc6. However, if we use a list or map instead of a vector, the program will crash without hesitation.
The correct method is as follows:
The erase implementation of all the containers in STL will return an iterator, which points to "the successor element of the currently deleted element, or end ()"
Therefore, after deleting an element through erase while traversing all elements of the container, the erase return value is assigned to the iteration variable.
Hope you can give me some advice ......