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

C++StlMapKeyErase

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

This is perfectly fine, mymap.erase('D') will return 0 in this case.

See http://www.cplusplus.com/reference/stl/map/erase.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfuadView Question on Stackoverflow
Solution 1 - C++rlbondView Answer on Stackoverflow
Solution 2 - C++brian-brazilView Answer on Stackoverflow