简体   繁体   English

在地图上 <string, int> ,是否保证int初始化为零?

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

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. 是的, std::map上的operator[]将使用T()初始化该值,在int的情况下,该值为零。

This is documented on section 23.4.4.3 of the C++ standard: 这在C ++标准的第23.4.4.3节中有记录:

 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. 效果 :如果地图中没有等效于x键,则将value_type(x, T())插入到地图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM