increment map<string, int> using ++ operator

C++MapOperators

C++ Problem Overview


I have a map to count the occurrence of words in a file. I am reading words from the file, and each time I read a word I want to do this:

map[word]++; //(where map is the name of my map, I'm not using map as a name of course)

so that if the my map already has 'word' as a key, it increments it, otherwise it creates the new key and increments it.

Here's where I am concerned: if I do map[word]++ on a new key (which is unavoidable in the first word read), will my program crash because the int in my map is unitialized? If so, what's the most efficient way of telling my map: if the word is already there, do ++ on the value, otherwise, create the new key with value = 1? Using an if statement with 'map.find' here seems unnecessarily redundant, what do you think?

Thanks

C++ Solutions


Solution 1 - C++

> will my program crash because the int in my map is unitialized?

No; if the element with key word doesn't exist, the element will be created and value initialized. A value-initialized int has a value of 0.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdozView Question on Stackoverflow
Solution 1 - C++James McNellisView Answer on Stackoverflow