What does the STL map[key] return if the key wasn't a initialized key in the map?

A default constructed std::string ins inserted into the std::map with key 'b' and a reference to that is returned.

It is often useful to consult the documentation, which defines the behavior of operator[] as:

Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type().

(The SGI STL documentation is not documentation for the C++ Standard Library, but it is still an invaluable resource as most of the behavior of the Standard Library containers is the same or very close to the behavior of the SGI STL containers.)


A default-constructed object (eg, an empty string in this case) is returned.

This is actually returned even when you say map['a'] = "ahh!!";. The [] operator inserts a default-constructed string at position 'a', and returns a reference to it, which the = operator is then called on.


std::map operator[] inserts the default constructed value type in to the map if the key provided for the lookup doesn't exist. So you will get an empty string as the result of the lookup.

Tags:

C++

Stl

Map