0

Let's say I wanted to construct an std::unordered_map<char, int> to map the frequency of characters in a string. I would do something like

char* myString;
std::unordered_map<char, int> hashmap;
for(char* pch = myString; *pch !=0 ; pch++)
{
     hashmap[*pch]++;
}

This, to me, feels dangerous as how do I know hashmap[*pch]++ will construct an integer in the value of the hashmap entry that starts at 0? Where do I find this guarantee (if it exists)?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • 3
    You can find the guarantee by reading documentation. It's perfectly safe because `unordered_map::operator[]` will first insert a value initialized `int`, i.e. `0`, if the key doesn't exist. – Praetorian Jan 23 '18 at 04:47

1 Answers1

1

The usual reference for the language and standard library covers this at least if you follow the link to value initialization as Praetorian mentioned. See also Is the value of primitive types in std::map initialized? (for which the answer is the same).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76