为什么要使用 `std::map::find` 来检查映射是否有键?
Why use `std::map::find` for checking if maps have a key?
我最近发现(不是通过研究,所以如果这是错误的请告诉我,我会更正)以下方法以某种方式起作用:
std::map<T*, U*> map;
std::cout << map[key_that_is_not_in_map] << std::endl;
// OUTPUT:
// 0
不过很多人推荐使用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?
Yes,std::map::operator[]
如果key不存在则执行插入。而 std::map::find
没有。
来自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.
我最近发现(不是通过研究,所以如果这是错误的请告诉我,我会更正)以下方法以某种方式起作用:
std::map<T*, U*> map;
std::cout << map[key_that_is_not_in_map] << std::endl;
// OUTPUT:
// 0
不过很多人推荐使用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?
Yes,std::map::operator[]
如果key不存在则执行插入。而 std::map::find
没有。
来自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.