Here is some example code:
#include<iostream>
#include<map>
#include<string>
using namespace s开发者_如何学编程td;
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?
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 objectdata_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.
If you try to access a key value using indexing operator []
, then 2 things can happen :
- The map contains this key. So it will return the corresponding key value
- The map doesn't contain the key. In this case it will
automatically add a key
to the map withkey 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
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.
精彩评论