Use std::map to calculate density of elements

Often there might be a need to calculate how many times each element from a particular collection appears in that collection. For example, having a string, we might want to how many times each letter appears, or how many times each word appears, or having a vector of numbers, we may ask how many times each number appears, etc.

It is easy to use std::map where a key is an element (letter, word, etc.), and value is the counter. The implementation is simple and looks like this.

std::map<char, int> get_char_density()
{
  std::stringstream ss{ "this is a testing string" };
  char letter;
  std::map<char, int> density;

  while (ss >> letter)
  {
    ++density[letter];
  }
  return density;
}

In this case, I use stringstream and bind it to the string. It then allows me to traverse the string as a stream via while loop. In the real world, the string would probably go from some external resource, for example from a file.

Here I count each word in the file and store it.

std::map<std::string, int> word_counter()
{
  std::ifstream source{ "path/to/file.txt" };
  std::string word_read;
  std::map<std::string, int> dictionary;
  if (!source) std::cerr << "error source file\n";

  while (source >> word_read)
  {
    ++dictionary[word_read];
  }	
  source.close();
  return dictionary;
}

In any case, I use std::map and streams for traversing in a while loop.