本文介绍了C ++计数实例/直方图使用std :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到类似于以下的示例代码:
I have seen sample code similar to the following:
std::string s = "Hello World!";
std::map<char, std::size_t> h;
for (std::string::const_iterator i=s.cbegin(); i!=s.cend(); ++i)
{
++h[*i];
}
assert(h['l'] == 3);
这似乎依赖于每个字母的第一次出现的值类型为零。即使使用类似 std :: size_t
的东西也是如此,它没有默认的构造函数将其重置为零?
This seems to rely on the value type being zeroed on the first occurence of each letter. Is this guaranteed even when using something like a std::size_t
which has no default constructor resetting it to zero?
推荐答案
确实这就是 map
的工作原理: []
-operator正在变化并且如果它不存在,将创建映射类型的对象。由于 size_t
value-初始化为零,所以您都可以。
Indeed that's how map
works: The []
-operator is mutating and will create the object of mapped type if it does not exist yet. Since size_t
value-initializes to zero, you're all fine.
这篇关于C ++计数实例/直方图使用std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!