Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map<string,int> default initialization of value [duplicate]

This piece of code seems work well, with default value for they value_type (int) as 0; does it work for all cases?

std::map<std::string,int> w;
for (const auto& t: str)
   w[t]++;

What about double? map? default 0.0?

like image 802
wenfeng Avatar asked Apr 23 '13 19:04

wenfeng


2 Answers

Yes, this code would work for any type of the key, including double. The reason this works is that the non-const operator [] returns a reference to the value at the key, not a copy of that value. It is that reference to which the ++ operator gets applied.

The code fragment that you show works as follows:

  • For each key t of type string in the str container,
  • The map w is searched for the given key
  • Since the entry is not there, a new one gets inserted into the map
  • Since the key of the entry is known, but the value is not, a default (value-initialized, e.i. 0 for int) object for the value gets created
  • A reference to the newly created object (in this case, int& initialized to zero) is returned to the caller
  • The ++ operator is applied to the reference returned from the [], which changes 0 to 1 (or 0.0 to 1.0, etc.)
like image 76
Sergey Kalinichenko Avatar answered Oct 01 '22 21:10

Sergey Kalinichenko


Yes. When you use the []-operator on a map and no element with the desired key exists, a new element is inserted which is value-initialized. For an integer, this means initialized to zero.

like image 28
Kerrek SB Avatar answered Oct 01 '22 20:10

Kerrek SB