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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.