C++ STL map::erase 一个不存在的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/695754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:49:05  来源:igfitidea点击:

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

c++stlmapkeyerase

提问by fuad

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

关于 C++ STL 映射,按键擦除:-

 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

干杯

回答by rlbond

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.

是的,事实上,std::map::erase()返回一个 size_type 表示删除的键数。因此,对于未擦除的内容返回 0,对于已擦除的地图返回 1。

回答by brian-brazil

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

这完全没问题,在这种情况下 mymap.erase('D') 将返回 0。

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

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