c++ - map<string, int>中,是否保证int初始化为0?

标签 c++ stdmap

比如统计书中单词出现的次数,我看到有人简单的写了:

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, inserts value_type(x, T()) into the map.

关于c++ - map<string, int>中,是否保证int初始化为0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627805/

相关文章:

c++ - 需要有关 OOP 设计的帮助,以便在类之间共享变量,这些变量独立地使用计时器运行

c++ - 显示浮点的 ieee 32 位表示...指针输出的奇怪行为

c++ - 当映射包含字符串 vector 作为值时从值中获取键的有效方法

c++ - 'pair' 之前的预期主表达式

C++ std::map 持有任何类型的值

c++ - 计算并发读取流中不同元素的数量

c++ - C++ 错误处理的正确方法是什么

c++ - 甚至来自代码块的意外行为(mingw32-g++)

c++ - 有没有办法使用 std::copy 复制不冲突的映射值?

c++ - mpi程序的gui