C++ Notes: STL Containers - map example

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

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
// map/wordfreq.cpp - Word frequencies using set and map.
// Fred Swartz 2001-12-11, 2004-02-29
//
// Words to ignore are read from a file and saved in a set<string>.
// Words to count are read from cin and counted in a map<string, int>.

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

//========================================================= main
int main() {

    set<string> ignore;    // Words to ignore.
    map<string, int> freq; // Map of words and their frequencies
    string word;           // Used to hold input word.
    
    //-- Read file of words to ignore.
    ifstream ignoreFile("ignore.txt");
    while (ignoreFile >> word) {
        ignore.insert(word);
    }

    //-- Read words/tokens to count from input stream.
    while (cin >> word) {
        if (ignore.find(word) == ignore.end()) {
            freq[word]++; // Count this.  It's not in ignore set.
        }
    }

    //-- Write count/word.  Iterator returns key/value pair.
    map<string, int>::const_iterator iter;
    for (iter=freq.begin(); iter != freq.end(); ++iter) {
        cout << iter->second << " " << iter->first << endl;
    }

    system("PAUSE");  // keep console window open in DevC++.
    return 0;
}//end main

Exercises

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