Should I use ++ wordCount [key] for unordered_map <string, int> when the key does not exist in wordCount?

See the code below:

unordered_map<string, int> wordCount;
for(string word: words)
    ++wordCount[word];

Question:

Should I use it here ++wordCount[word];when words do not exist in wordCount? I have always seen someone use this, but I'm not sure about it.

The explanation here said:

If k does not match the key of any element in the container, the function inserts a new element with this key and returns a link to its displayed value. Please note that this always increases the container size by one, even if the item has no associated value (the item is created using its default constructor).

and I know that int is not initialized by default . So, I think it’s not safe to increase the value of the map right so, right?

+4
source share
1 answer

Quoting cppreference documents on operator[]

When the default allocator is used, this causes the key to be copied from the key, and the displayed value is initialized with the value.

Keyword value initialized . that the initialized value is zero. int

Here's the official link (C ++ 14, 23.5.4.3, clause 2, [unord.map.elem]):

: unordered_map , k, value_type(k, mapped_type()), value_type(std::move(k), mapped_type()).

mapped_type(), mapped_type = int int.

+5

All Articles