The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home File Input/Output and pmatrices A Proper Distance Matrix | ||
A Proper Distance Matrix
Although this code works, it is not as well organized as it should be. Now that we have written a prototype, we are in a good position to evaluate the design and improve it. What are some of the problems with the existing code?
Here is a draft of what the header for a DistMatrix might look like: class DistMatrix {private: Set cities; pmatrix<int> distances; public: DistMatrix (int rows); void add (const pstring& city1, const pstring& city2, int dist); int distance (int i, int j) const; int distance (const pstring& city1, const pstring& city2) const; pstring cityName (int i) const; int numCities () const; void print (); }; Using this interface simplifies main: void main (){ pstring line; ifstream infile ("distances"); DistMatrix distances (2); while (true) { getline (infile, line); if (infile.eof()) break; processLine (line, distances); } distances.print (); } It also simplifies processLine: void processLine (const pstring& line, DistMatrix& distances){ char quote = '\"'; pvector<int> quoteIndex (4); quoteIndex[0] = line.find (quote); for (int i=1; i<4; i++) { quoteIndex[i] = find (line, quote, quoteIndex[i-1]+1); } // break the line up into substrings int len1 = quoteIndex[1] - quoteIndex[0] - 1; pstring city1 = line.substr (quoteIndex[0]+1, len1); int len2 = quoteIndex[3] - quoteIndex[2] - 1; pstring city2 = line.substr (quoteIndex[2]+1, len2); int len3 = line.length() - quoteIndex[2] - 1; pstring distString = line.substr (quoteIndex[3]+1, len3); int distance = convertToInt (distString); // add the new datum to the distances matrix distances.add (city1, city2, distance); } I will leave it as an exercise to you to implement the member functions of DistMatrix.
|
||
Home File Input/Output and pmatrices A Proper Distance Matrix |