C++ STL map::erase a non-existing key

fuad picture fuad · Mar 30, 2009 · Viewed 24.9k times · Source

Regarding the C++ STL map, erasing by key:-

 size_type map::erase ( const key_type& x );

Is it legal to erase a non-existing key? i.e. is the snippet below ok?

map<char,int> mymap;
mymap['c']=30;
mymap.erase('c');
mymap.erase('c');
mymap.erase('D');

Cheers

Answer

rlbond picture rlbond · Mar 30, 2009

Yes, in fact, std::map::erase() returns a size_type which indicates the number of keys erased. Thus it returns 0 for nothing erased and 1 for something erased for a map.