简体   繁体   中英

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

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? ie is the snippet below ok?

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

Cheers

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM