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?
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.
Quoting MSDN:
So, assuming that map creates new entries at missing keys using a default constructor then yes, size_t will be initialised to zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With