// maintains a word and its frequency of occurrence
class wordFreq
{
public:
// initialize word and set freq to 1
wordFreq(const string& str): word(str), freq(1)
{}
// add 1 to the frequency
void increment()
{ freq++; }
// equality operator compares the word for the objects
friend bool operator== (const wordFreq& lhs, const wordFreq& rhs)
{ return lhs.word == rhs.word; }
// less than operator compares the word for the objects
friend bool operator< (const wordFreq& lhs, const wordFreq& rhs)
{ return lhs.word < rhs.word; }
// output an object in the format: word (freq)
friend ostream& operator<< (ostream& ostr, const wordFreq& w)
{
ostr << w.word << " (" << w.freq << ')';
return ostr;
}
private:
string word;
// number of times word found
int freq;
};
int main()
{
ifstream fin;
// words read from file and inserted into wf
list<wordFreq> wf;
// use for seqSearch() and displaying the list
list<wordFreq>::iterator iter;
// prompt for the name of the file
string fileName, word;
cout << "Enter the name of the file containing the words: ";
cin >> fileName;
// error checking
fin.open(fileName.c_str());
if (!fin)
{
cerr << "Cannot open " << fileName << endl;
exit(1);
}
// read a word until end-of-file
while (fin >> word)
{
// declare a wordFreq object with frequency 1
wordFreq obj(word);
// search for word in the list wf
iter = seqSearch<wordFreq> (wf.begin(), wf.end(), obj);
// did we locate the word?
if (iter != wf.end())
// yes. increment the word frequency
(*iter).increment();
else
// word is new. insert obj into the list
wf.push_back(obj);
}
// list member function sort() orders the list
wf.sort();
// output each object on a separate line
cout << endl;
writeList(wf, "\n");
system("pause");
return 0;
}
template <typename T>
list<T>::iterator seqSearch(list<T>::iterator first,
list<T>::iterator last, const T& target)
{
// start at location first
list<T>::iterator iter = first;
// compare list elements with item until either
// we arrive at last or locate item
while(iter != last && !(*iter == target))
iter++;
// iter either points at item or is last
return iter;
}