C++ Notes: STL Containers - map example

This program reads "words" from cin and prints how many times each occurs.

// Word frequencies -- using map
// Fred Swartz 2001-12-11

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> freq; // map of words and their frequencies
    string word;           // input buffer for words.

    //--- Read words/tokens from input stream
    while (cin >> word) {
        freq[word]++;
    }

    //--- Write the count and the word.
    map<string, int>::const_iterator iter;
    for (iter=freq.begin(); iter != freq.end(); ++iter) {
        cout << iter->second << " " << iter->first << endl;
    }
    return 0;
}//end main

Exercises

  1. Clean up the "words" to remove punctuation, ignore numbers, etc.
  2. Read input from a file.
  3. Read another file of words to ignore.
  4. Sort the list from the most frequent to the least frequent.