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 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, insertsvalue_type(x, T())
into the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With