Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does STL Map auto-initialize values? [duplicate]

Tags:

c++

map

stl

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?

like image 410
Casey Patton Avatar asked Oct 15 '12 04:10

Casey Patton


2 Answers

Quoth the standard:

ISO/IEC 14882 §23.4.4.3

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.

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.

like image 192
John Calsbeek Avatar answered Sep 17 '22 16:09

John Calsbeek


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.

like image 45
xtofl Avatar answered Sep 21 '22 16:09

xtofl