C++ counting instances / histogram using std::map

微笑、不失礼 提交于 2019-11-28 08:35:20

问题


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);

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?


回答1:


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.




回答2:


Quoting MSDN:

POD and scalar types will always be zero initialized if instantiated with the default constructor syntax.

So, assuming that map creates new entries at missing keys using a default constructor then yes, size_t will be initialised to zero.



来源:https://stackoverflow.com/questions/8010761/c-counting-instances-histogram-using-stdmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!