Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Counting Map

Recently I was dealing with what I am sure is a very common problem, which essentially boils down into the following:

Given a long text, calculate the frequency of each word occurring in the text.

I was able to solve this problem using std::unordered_map. This, however, turned quite ugly, as for every word in the text, if that's already been encountered I had to do a find, erase, and then a re-insert into the map with the value incremented.

I realise there are other ways of doing this, such as using a hashing function on top of a vanilla array/vector and increment value there, but I was wondering if there was a more elegant way of solving this problem, like an STL component, or function. that would have a similar interface to Pythons Counter collections.

I know C++ being C++ I can't really expect such high level concepts to always be implemented for me, but was just wondering if you guys new about anything (or at least your Googling skills are superior to mine) which could make my code a little nicer.

like image 813
Tomasz Kaminski Avatar asked Nov 28 '15 19:11

Tomasz Kaminski


People also ask

What does count do in map?

map count() function in C++ STL Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.

What is the use of map count in C++?

What is map::count()? The map::count( ) is a function which comes under <map> header file. This function counts the elements with specific key, it returns 1 if the element with key is present, It returns the 0 if the element with key is not present in container.

How do you find the number of elements on a map?

Use the size() method to get the count of elements.

What is map in C ==?

Maps are the associative containers that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but cannot be altered. Values associated with keys can be changed. For example: A map of Employees where employee ID is the key and name is the value can be represented as: Keys. Values.


1 Answers

I'm not quite sure why an std::unordered_map (or just std::map) would involve much complexity. I'd write the code something like this:

std::unordered_map<std::string, int> words;

std::string word;
while (word = getword(input))
   ++words[word];

There's no need for any kind of find/erase/reinsert.

In case it's not clear how/why this works: operator[] will create an entry for a value if none exists yet in the map. The associated value will be a value-initialized object of the specified type, which will be zero in the case of an int (or similar). We then increment that every time we encounter the word.

like image 157
Jerry Coffin Avatar answered Sep 22 '22 13:09

Jerry Coffin