Std :: map <string, int> initialization of the default value

This piece of code works well, with the default value for them value_type( int) as 0; Does this work for all occasions?

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

How about a double? map? default 0.0?

+5
source share
3 answers

Yes, this code will work for any type of key, including double. The reason for this is that non-const operator []returns a reference to the value in the key, and not to a copy of this value. This is the link to which the statement applies ++.

The selected code fragment works as follows:

  • t string str
  • w
  • , .
  • , ,
  • ( int&, )
  • ++ , [], 0 1 ( 0.0 1.0 ..)
+5

. [] - , , , . .

+6

?

, T().

T , int double, .

T - , .

+1

All Articles