increment map<string, int> using ++ operator
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
Solution 1:
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
.