Accelerated C++ Solution to Exercise 7-0 (Part 1 / 3)

This is part 1 of the 3-part Exercise 7-0. Click here to see the other parts.

Exercise 7-0 (Part 1 / 3)

Use associative arrays to count words – in this particular exercise, we shall use the map from the standard library.

Solution

Section 7.2 (Page 124) of the textbook contains a very nice and compact main function that performs easy word counting with associating arrays using the map utility. The program is very easy to understand. See the text book for detail description.

#include <iostream>   // std::cin, std::cout, std::endl
#include <map>        // std::map
#include <string>     // std::string

using std::cin;
using std::cout;
using std::endl;
using std::map;
using std::string;

int main()
{
  string s;
  map<string, int> counters;  // store each word and an associated counter

  // read the input, keeping track of each word and how often we see it
  while (cin >> s)
    ++counters[s];

  // write the words and associated counts
  for (map<string, int>::const_iterator it = counters.begin();
       it != counters.end(); ++it)
    cout << it->first << "\t" << it->second << endl;

  return 0;
}

Test Program

I now submit some words to the console input upon running the program. The program quickly counts the words and display results as expected.

apple orange banana
orange orange
apple banana
mango
^Z
apple   2
banana  2
mango   1
orange  3

One more thing to note is that the associative array automatically sort the key of the key-value pair. i.e. the pair<const K, V>.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000