The deletion element operation of the sequential container was recently used, and the considerations for the function are hereby recorded.
In C++primer, the C.erase (p) is explained in this way:
c.erase (p) Removes the element that the iterator p points to, returns an iterator that points to the element after the element being deleted, and if p points to the tail element, returns the trailing iterator, which produces undefined behavior if p is the trailing iterator.
This function I found in the process of using a little bit of attention
If you want to traverse a container and delete an element that does not meet the requirements, it is best to use while instead of using the for
Because
Vector<rotatedrect>::iterator it =M_rect.begin (); while((IT)! =M_rect.end ()) { floatdiff = ABS ((*it). Size.width-(* (IT +1) . Size.width); if(diff >Diffmax) { if((It-m_rect.begin ()) < (M_rect.size ()/2)) it =M_rect.erase (it); when the pointer is already pointing to the next element, the pointer does not need to be self-increment Elseit = m_rect.erase (it +1); }Else{It++; //The pointer is increased by one, while the loop can select conditionally to point the pointer to the next element } }
Vector<rotatedrect>::iterator it =M_rect.begin (); for (;(it)! = M_rect.end (); it++)//If you are using a for loop, and you choose to increment one from here
{ floatdiff = ABS ((*it). Size.width-(* (IT +1) . Size.width); if(diff >Diffmax) { if((It-m_rect.begin ()) < (M_rect.size ()/2)) it =M_rect.erase (IT); //Then it will be repeated with the self-increment here, which will cause the element to be skipped Elseit = m_rect.erase (it +1); } }
When I consulted the information, I found a blogger recommended the way
Link Here http://blog.csdn.net/zhuimengzh/article/details/6841500
voidFun () {vector<int>IVec; Vector<int>:: Iterator it; for(intI=0;i<Ten; i++) Ivec.push_back (i); Display (IVEC); for(It=ivec.begin (); It!=ivec.end (); + +it) { if(*it = =4|| *it = =7) {It=Ivec.erase (IT); --it;//here 's a//******. The blogger recommends automatically returning one here, which seems to be possible with a for loop, but it's not. }} display (IVEC);}
If you delete the element that is the first element of the container, then the behavior of the fallback will be undefined, remember
Precautions for using C + + vector erase functions