在map中,是否保证int初始化为零?
比如,统计一下书中的单词出现次数,我看到有人简单地写道:
map<string, int> count;
string s;
while (cin >> s) count[s]++;
这是正确的做法吗?我在我的机器上测试过,似乎是这样。但是初始化为零能保证吗?如果不是,我会想象这样的代码:
map<string, int> count;
string s;
while (cin >> s)
if (count.find(s) != count.end()) count[s]++;
else count[s] = 1;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,
std::map
上的operator[]
将使用T()
初始化值,在int 的情况下
,为零。C++ 标准第 23.4.4.3 节对此进行了记录:
Yes,
operator[]
on astd::map
will initialize the value withT()
, which in the case ofint
, is zero.This is documented on section 23.4.4.3 of the C++ standard: