Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment map<string, int> using ++ operator

Tags:

c++

operators

map

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

like image 947
Edoz Avatar asked Apr 11 '11 03:04

Edoz


People also ask

How do you increment a map element?

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 .

How do you increase increments in C++?

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.

How increase HashMap count in Java?

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);

How do I change the value of a map in C++?

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.


1 Answers

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.

like image 67
James McNellis Avatar answered Sep 21 '22 22:09

James McNellis