简体   繁体   English

为什么使用`std::map::find` 来检查地图是否有密钥?

[英]Why use `std::map::find` for checking if maps have a key?

I recently found out (not through research, so if this is wrong please tell me and I will correct this) that the following somehow works:我最近发现(不是通过研究,所以如果这是错误的,请告诉我,我会更正)以下方法有效:

std::map<T*, U*> map;
std::cout << map[key_that_is_not_in_map] << std::endl;
// OUTPUT:
// 0

However a lot of people recommend using std::map::find(key_.....):= std::map::end() .但是很多人建议使用std::map::find(key_.....):= std::map::end()

Is there something about the latter that makes it safer, or is the first only applicable to pointers keys and values?后者是否有一些使它更安全的东西,还是第一个仅适用于指针键和值?

Is there something about the latter that makes it safer, or is the first only applicable to pointers keys and values?后者是否有一些使它更安全的东西,还是第一个仅适用于指针键和值?

Yes , std::map::operator[] performs an insertion if no key exists.的,如果不存在密钥, std::map::operator[]执行插入。 And the std::map::find does not.std::map::find没有。

From cppreference.com the std::map::operator[]cppreference.com std::map::operator[]

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist .返回对映射到与 key 等效的 key 的 value 的引用,如果这样的 key 不存在,则执行插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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