What happens if I read a map's value where the key does not exist?

c++, dictionary

Solution

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.

Problem

``` map<string, string> dada; dada["dummy"] = "papy"; cout << dada["pootoo"]; ``` I'm puzzled because I don't know if it's considered undefined behaviour or not, how to know when I request a key which does not exist, do I just use find instead ?

Original source