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;
Yes,
operator[]on astd::mapwill initialize the value withT(), which in the case ofint, is zero.This is documented on section 23.4.4.3 of the C++ standard: