On the map <string, int>, is int initialization guaranteed to be zero?

For example, count the occurrence of a word in a book, I saw that someone just wrote:

map<string, int> count; string s; while (cin >> s) count[s]++; 

Is this the right way to do this? I tested on my car and it seems so. But is zero initialization guaranteed? If this is not the case, I would suggest code like this:

 map<string, int> count; string s; while (cin >> s) if (count.find(s) != count.end()) count[s]++; else count[s] = 1; 
+7
source share
1 answer

Yes, operator[] in std::map initializes the value with T() , which in the case of int is zero.

This is described in section 23.4.4.3 of the C ++ standard:

 T& operator[](const key_type& x); 

Effects: if there is no key equivalent to x on the card, inserts value_type(x, T()) into the card.

+12
source

All Articles