0

Why the follwoing code is failing ?

typedef vector<SOCKET /*socket*/> UIConnection;

UIConnection::iterator itrUICon;

for ( itrUICon = m_ListUIConnection.begin();itrUICon != m_ListUIConnection.end();itrUICon++)
{
    if (*itrUICon == nSock)
    {           
        itrUICon = m_ListUIConnection.erase(itrUICon);          
    }
}
0

2 Answers 2

6

You must remove the ++itrUICon in the for instruction.

UIConnection::iterator itrUICon;

for ( itrUICon = m_ListUIConnection.begin();itrUICon != m_ListUIConnection.end(); )
{
    if (*itrUICon == nSock)
    {           
        itrUICon = m_ListUIConnection.erase(itrUICon);          
    }
    else ++itrUICon;
}
8
  • Dang, right! I remember that one from my last project actually.
    – Xeo
    May 16, 2011 at 6:46
  • @Simone: Probably a random drive-by. I received one at about the same time as yours.
    – CB Bailey
    May 16, 2011 at 6:51
  • @Charles I see. I didn't know that things like that happens on SO too
    – Simone
    May 16, 2011 at 6:56
  • Calling erase on a vector invalidates all iterator and references to elements after position - can you explain why your code works?
    – Martin Ba
    May 16, 2011 at 6:57
  • 3
    @Martin from your link: "Return value: A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.".
    – Simone
    May 16, 2011 at 6:58
4

Probably because you are erasing the last item in the vector and then incrementing itrUICon in the increment part of the for statement when it is already equal to .end().

Prefer using the erase()/std::remove() idiom or at least move the increment out of the for statement and only perform it if you didn't preform an erase.

2
  • charles will this work for map as well.typedef map<unsigned long /*mac id */ ,int /*socket*/> GatewayConnection; May 16, 2011 at 7:01
  • @Chris_vr: For std::remove won't work for associative containers because they preserve order. You can do mp.erase(it++); instead because erasing an element from a map doesn't invalidate any iterators other than those pointing to the element removed.
    – CB Bailey
    May 16, 2011 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.