What happens if I read a map's value where the key does not exist?
The map::operator[]
searches the data structure for a value corresponding to the given key, and returns a reference to it.
If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the map::at
function instead.)
You can get a full list of methods of std::map here:
http://en.cppreference.com/w/cpp/container/map
Here is the documentation of map::operator[]
from the current C++ standard...
23.4.4.3 Map Element Access
T& operator[](const key_type& x);
Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
T& operator[](key_type&& x);
Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.
Requires: mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
If you try to access a key value
using index operator []
, then 2 things can happen :
- The map contains this
key
. So it will return the correspondingkey value
. - The map doesn't contain the
key
. In this case, it will automatically add akey
to the map withnull value
.
"pootoo"
key does't exist in your map. So it will automatically add this key
with value = ""
(empty string). And your program will print empty string.
Here map size will increase by 1
.
To search a key you can use map_name.find()
, which will return map_name.end()
if the key doesn't exist. And no extra key
will be added.
You can use []
operator when you want to set value for a key.
It's not undefined behavior. If operator []
doesn't find a value for the provided key, it inserts one at that position.