What does the STL map[key] return if the key wasn&

2020-07-01 11:17发布

问题:

Here is some example code:

 #include<iostream>
 #include<map>
 #include<string>
 using namespace std;

 int main()
 {
   map<char, string> myMap;
   myMap['a'] = "ahh!!";
   cout << myMap['a'] << endl << myMap['b'] << endl;
   return 0;
 }

In this case i am wondering what does myMap['b'] return?

回答1:

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



回答2:

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.



回答3:

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.



回答4:

If you try to access a key value using indexing operator [], then 2 things can happen :

  1. The map contains this key. So it will return the corresponding key value
  2. The map doesn't contain the key. In this case it will automatically add a key to the map with key value null.

As 'b' key is not in your map so it will add this key with value ""(empty string) automatically and it will print this empty string.

And here map size will increase by 1

So to look-up for a key you can use .find(), which will return map.end() if the key is not found.
And no extra key will be added automatically

And obviously you can use [] operator when you set a value for a key