Code:
/*
* failure.cpp
*
* Created on: Sep 27, 2011
* Author: mike
*
* failure.cpp - A program to read in words from stdin, tally their frequency, and add frequencies to
* tally up the total number of words
*/
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
/*
* A function object that tallies the value elements of map pairs
*/
class Frequency_works {
private:
int* total;
public:
Frequency_works(int& x) : total(&x) {}
void operator() (const pair<const string, int>& elem) {*total += elem.second;}
};
/*
* A function object that tallies the value elements of map pairs
*/
class Frequency_fails {
private:
int total;
public:
Frequency_fails(int x = 0) : total(x) {}
void operator() (const pair<const string, int>& elem) {
total += elem.second;
//cout << total << ' '; // For testing
}
int getTotal() {return total;}
};
/*
* Reads words into a map from stdin, and accumlates their frequency
*/
void get_words ( map <string,int>& words) {
string tmp;
// While there is input, read from stdin
while (cin >> tmp && tmp != "DONE") {
words[tmp]++; // Record word and frequency
}
}
int main () {
int total = 0;
Frequency_works f1(total);
Frequency_fails f2;
map<string, int> w;
get_words (w);
// Tally and print total words, using function object of class Frequency_works
for_each (w.begin(), w.end(), f1);
cout << "Total words (Frequency works): " << total << '\n';
//Tally and print total words, using function object of class Frequency_fails
for_each (w.begin(), w.end(), f2);
cout << "Total words (Frequency fails): " << f2.getTotal() << '\n';
return 0;
}
OUTPUT (using the words I give as I describe how to use below)
Code:
Total words (Frequency works): 5
Total words (Frequency fails): 0
To use the program, just feed it a list of words, preferably with certain words repeated, on stdin. End with the word DONE. Like so.
Code:
./executable
box
box
hammer
hammer
nail
DONE
When you are finished, you can tell me why Frequency_fails doesn't do its job as a function object.