Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider:

#include <map>

int main()
{
    std::map< int, int > m;
    m[ 0 ] = 0;
    m[ 1 ] = 1;

    m.erase( 0 );  // ok
    m.erase( 2 );  // no-op
    m.erase( m.find( 2 ) );  // boom!
}

(OK, so the title talks abouting erasing an end() iterator, but find will return end() for a non-existent key.)

Why is erasing a non-existent key OK, yet erasing end() blows up. I couldn't see any explicit mention of this in the standard?

I've tried this on VS2005 (throws an exception in debug configuration) and GCC 4.0.1 (100% CPU). Is it implementation dependent?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
366 views
Welcome To Ask or Share your Answers For Others

1 Answer

For erase(key), the standard says that all elements with value key are removed. There may of course be no such values.

For erase(it) (where it is a std::map::iterator), the standard says that the element pointed to by it is removed - unfortunately, if it is end() it does not point to a valid element and you are off in undefined behaviour land, as you would be if you used end() for any other map operation. See section 23.1.2 for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...