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
Increment map value associated with a key in C++ Once the key is found, we can increment its value using the ++ operator on the second member function of the pair pointed by the iterator. If the key is not found, we can insert it into the map with value 1 using unordered_map::insert with std::make_pair .
In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable.
Show activity on this post. Map<String, Integer> map = new HashMap<>(); String key = "a random key"; int count = map. getOrDefault(key, 0); // ensure count will be one of 0,1,2,3,... map. put(key, count + 1);
To update an existing value in the map, first we will find the value with the given key using map::find() function. If the key exists, then will update it with new value.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With