Possible Duplicate:
Why does a class used as a value in a STL map need a default constructor in …?
When I'm using a map, do values definitely get initialized to defaults or should I not rely on this?
For example, say I have the following code:
map<string, int> myMap;
cout << myMap["Hey"];
This will output "0" with my compiler. Is this guaranteed behavior? Is it possible that this wouldn't always initialize to 0?
Quoth the standard:
ISO/IEC 14882 §23.4.4.3
T& operator[](const key_type& x);
- Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map.- Requires:
key_type
shall beCopyConstructible
andmapped_type
shall beDefaultConstructible
.- Returns: A reference to the
mapped_type
corresponding tox
in*this
.- Complexity: logarithmic.
So, not only is it guaranteed, but evaluating myMap["Hey"]
also causes the value 0 to be inserted into the map, if there was no entry for it before.
It value constructs the value for a new key. Take a look at some documentation:
A call to this function is equivalent to:
insert(
make_pair(x,T())
);
This will translate into
insert(make_pair("Key", int()));
So yes: your values will be zero at first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With