c++algorithmdictionaryfindstdmap

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().

Is there something about the latter that makes it safer, or is the first only applicable to pointers keys and values?


Solution

  • 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. And the std::map::find does not.

    From cppreference.com the 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.