Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...