设计程序的好习惯,首先是把程序所涉及的操作列出来。
分析了程序支持的任务:
以下为书中例子。
- It must allow the user to indicate the name of a file to process. The program will store the contents of the file so that we can display the original line in which each word appears.
- The program must break each line into words and remember all the lines in which each word appears. When it prints the line numbers, they should be presented in ascending order and contain no duplicates.
- The result of querying for a particular word should be the line numbers on which that word appeared.
- To print the text in which the word appeared, it must be possible to fetch the line from the input file corresponding to a given line number.
再分析数据结构:
以下也是书中的例子。
巧妙的用一个TextQuery类来实现这个程序。加上一些容器的使用,可以很巧妙的完成上面的任务。
- We'll use a vector<string> to store a copy of the entire input file. Each line in the input file will be an element in this vector . That way, when we want to print a line, we can fetch it by using the line number as an index.
- We'll store each word's line numbers in a set . Using a set will guarantee that there is only one entry per line and that the line numbers will be automatically stored in ascending order.
- We'll use a map to associate each word with the set of line numbers on which the word appears.
- 综上所述,一个TextQuery类里面有两种数据成员:存储文件的vector对象,以及一个map容器对象。