The following is C++ code to get a count of the words in magazine. I'm trying to add the word if its value does not exist and if it does, increment it.
unordered_map<string,int>hash;
vector<string> magazine(m);
for(int i = 0;i <m;i++)
{
cin >> magazine[i];
if(hash[magazine[i]]>0)
hash[magazine[i]]++;
else
hash.emplace(magazine[i],1);
}
But when I try to output, all magazine key gives 0 as value. Any idea why?
Your version doesn't work because this if(hash[magazine[i]]>0)
will insert an element into hash
if it doesn't exist, this new element will have a mapped value of 0
¹. Which means that hash.emplace(magazine[i],1);
is pointless here because there will always be an element at magazine[i]
now. Because its value will be 0
your hash[magazine[i]]++;
will never run either because the if
will never be true
. Leaving you with a map of i
elements, all with value 0
.
operator[]
returns a reference to the mapped value if there is one, if not, it inserts one and then returns that reference¹.
Which means that you can factor out the if
and just change it to:
for(int i = 0;i <m;i++)
{
cin >> magazine[i];
++hash[magazine[i]];
}
Which basically means : "Get a reference to the mapped value for key magazine[i]
, if none is found, insert one and give me that one. Increment this reference."
¹: If insertion occurs the element is value-initialized. Because your mapped value type is int
this will result into the mapped value being 0
after insertion.