Search code examples
c++dictionarystlordered-map

Strange behaviour of m.erase() function in c++?


int main(){
    map<int, int> m;
    m.insert({1,2});
    m.insert({2,3});
    m.insert({5,10});
    m.erase(m.find(3));
    for(auto &x: m){
        cout<<x.first<<" "<<x.second<<nl;
    }
}

Output:

1 2
5 10

As far as I know m.find(3) returns iterator to the m.end() if key is not found. Then why pair {2,3} is deleted?


Solution

  • The pair is deleted because you violated a pre-condition of std::map::erase

    iterator erase( const_iterator pos );
    iterator erase( iterator pos );
    

    The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

    Violating a pre-condition of a standard library function has undefined behavior. So deleting a seemingly random element is totally in line with that.