C ++ instance counter / bar chart using std :: map

I saw a 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, apparently, relies on the fact that the type of the value is reset to zero at the first occurrence of each letter. Is this guaranteed even when using something like std::size_t , which does not have a default constructor, resetting it to zero?

+4
source share
2 answers

Indeed, how map works: the [] operator mutates and creates an object of a matching type if it does not already exist. Since the size_t value is initialized to zero, you're fine.

+6
source

Quote MSDN :

PODs and scalar types will always be initialized to zero if they are created with the default constructor syntax.

So, assuming the card creates new entries in the missing keys using the default constructor, then yes, size_t will be initialized to zero.

+5
source

Source: https://habr.com/ru/post/1379652/


All Articles