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

前端 未结 7 1132
孤独总比滥情好
孤独总比滥情好 2020-12-05 12:24
map dada;
dada[\"dummy\"] = \"papy\";
cout << dada[\"pootoo\"];

I\'m puzzled because I don\'t know if it\'s considered

7条回答
  •  情话喂你
    2020-12-05 13:19

    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);

    1. Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

    2. Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.

    3. Returns: A reference to the mapped_type corresponding to x in *this.

    4. Complexity: logarithmic.

    T& operator[](key_type&& x);

    1. Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.

    2. Requires: mapped_type shall be DefaultConstructible.

    3. Returns: A reference to the mapped_type corresponding to x in *this.

    4. Complexity: logarithmic.

提交回复
热议问题