Delete STL container elements

About stl container to remove elements of the problem, the error code is as follows:

std::vector<struct> mFriendList;
...
std::vector<struct>::iterator iter = mFriendList.begin();
for ( ; iter != mFriendList.end(); ++iter)
{
    if (...)
        mFriendList.erase(iter);
}

 

Once I said to remember this question, I turn back to the code, I did not understand why, when the program execution only know if if is true then the program will certainly collapse.
Master's argument is: When an element is deleted easily, pointing to all the elements of the iterator becomes invalid. The above code, as long as the implementation of the erase (iter), then iter will become invalid, then the implementation of ++ iter would certainly be wrong.

It was concluded in line to see the following two:
1. Remove node for containers (map, list, set) element, the insert iterator will cause failure of the element, other elements are not affected iterator
2. For sequential remove elements of containers (vector, string, deque), insert operation will lead to point to the element and the iterator element behind the failure

summed up, and recall Once the code was to give me change, so the correct wording should be like this :
1. for node container

std::list<struct> mList;
...
std::list<struct>::iterator iter = mList.begin();
method 1:
for (; ITER =! mList.end ();) 
{

  IF (...)
  {
// Since only lead node of the current node type iterator fails, the delete node iterator after shift operation, because the other elements will not fail
    mList.erase (ITER ++ );
  }
  the else   { ++ ITER;   } } method: General node 2 sequential containers and container

    




for (; ITER =! mList.end ();) 
{

  IF (...)
  {// node as the current node only lead formula iterator fails, the delete node iterator after shift operation, because the other elements will not fail     
    path = mList.erase (path); 
  }
  Else
  {
    traveling ++;
  }

}
 

2. For sequential containers

std::vector<struct> mVector;
...
std::vector<struct>::iterator iter = mVector.begin();
for ( ; iter != mVector.end(); )
{
    if (...)
    {
        // here we have more to say, because the order itself and the container will make the elements behind the iterator fail, it is not a simple operation ++
         // the ERASE here Sequential container () will return immediately be removed elements effective iterator to the next element
         // and erase node type container () return value is void, which I feel amazing, really amazing! ! ! ! 
        = ITER mVector.erase (ITER);
    }
    else
    {
        ++ process;
    }
}

 

Note: the achievement of specific container to see the STL library, VS in earse types of containers are returned the next iteration pointer.

Guess you like

Origin www.cnblogs.com/hjbf/p/11003050.html