Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In map<string, int>, is it guaranteed that the int is initialized to zero?

Tags:

c++

stdmap

For example, count the occurrence the words in a book, I saw somebody simply wrote:

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

Is this the correct way of doing so? I tested on my machine and seems so. But is the initialization to zero guaranteed? If it is not, I would imagine a code like this:

map<string, int> count;
string s;
while (cin >> s)
    if (count.find(s) != count.end())  count[s]++;
    else count[s] = 1;
like image 653
John Yang Avatar asked Oct 02 '11 16:10

John Yang


1 Answers

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

This is documented on section 23.4.4.3 of the C++ standard:

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

Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

like image 62
R. Martinho Fernandes Avatar answered Oct 05 '22 07:10

R. Martinho Fernandes