比如统计书中单词出现的次数,我看到有人简单的写了:
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;
最佳答案
是的,std::map
上的 operator[]
将使用 T()
初始化值,在 的情况下code>int
,为零。
这记录在 C++ 标准的第 23.4.4.3 节中:
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.
关于c++ - map<string, int>中,是否保证int初始化为0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627805/