Lab 28
Lab 28
1 #ifndef LAB28_H
2 #define LAB28_H
3
4 template<typename T>
5 class Frequency
6 {
7 public:
8 Frequency(T val) : value(val), frequency(1)
9 {}
10
11 void increment()
12 { ++frequency; }
13
14 T getValue() const
15 { return value; }
16
27 #endif
Figure 1. /usr/local/2336/include/lab28.h
1 #include <iostream>
2 #include <fstream>
3 #include <cstdlib>
4 #include <vector>
5 #include <algorithm>
6 #include <lab28.h>
7
13 template<typename T>
14 vector<Frequency<T> > distribution(const vector<T>& v);
15
16 template<typename T>
17 ostream& operator<<(ostream& out, const vector<Frequency<T> >& v);
18
19 #include "lab28.cpp"
20
32 if (argc != 2)
33 {
34 cerr << "Usage: " << *argv << " InputFileName" << endl;
35 exit(EXIT_FAILURE);
36 }
37
38 fin.open(*(argv+1));
39 if (fin.fail())
40 {
41 cerr << "Couldn’t open input file: " << *(argv+1) << endl;
42 exit(EXIT_FAILURE);
43 }
44
50
61 vector<char> charVec;
62 vector<Frequency<char> > charVecDist;
63 char ch;
64
68 charVecDist = distribution(charVec);
69 cout << "Before Sorting by Frequency" << endl << charVecDist << endl;
70 sort(charVecDist.begin(), charVecDist.end());
71 cout << "After Sorting by Frequency" << endl << charVecDist << endl;
72
76 vector<string> wordVec;
77 vector<Frequency<string> > wordVecDist;
78 string word;
79
88 wordVecDist = distribution(wordVec);
89 cout << "Before Sorting by Frequency" << endl << wordVecDist << endl;
90 sort(wordVecDist.begin(), wordVecDist.end());
91 cout << "After Sorting by Frequency" << endl << wordVecDist << endl;
92
93 return EXIT_SUCCESS;
94 }
95
108 // Function rtrim removes whitespace and punctuation from the end
109 // of string s
110 string rtrim(string s)
111 {
112 if (s.length() == 0)
113 return s;
114 else if (isspace(*(s.end() - 1)) || ispunct(*(s.end() - 1)))
115 return rtrim(s.substr(0, s.length() - 1));
116 else
117 return s;
118 }