samedi 20 juillet 2013

Counting occurence and histogram

A recurrent question on Stackoverflow [c++] is, hopw can we count word, sentence in string or a text file, or how can we build an histogram showing all unique number in a list and their number of occurence.

In fact every time those question found quite the same answer because in all case, whatever you want count, it can be really easy to do with C++ and STL. If we use the std::map class we can do that in 2 loop.

First, imagine we have a list containing random number.


srand(time(NULL));
std::vector list;
int N = 1 , M = 100;

for (int i = 0; i < M; ++i) { int rnd = M + rand() / (RAND_MAX / (N - M + 1) + 1); list.push_back(rnd); }


Ok, so now we have 100 number with some redundancy, let's count that with a map.


std::map histo;

for (auto rnd : list)
{
histo[rnd] += 1;
}


And it's done !, nothing else .... Just a loop to display the result:


for(auto var = begin(histo) ; var != end(histo) ; ++var)
{
std::cout << var->first << " have " << var->second << " occurence " << std::endl; }


Simple and efficient

Aucun commentaire :

Enregistrer un commentaire