我的Github地址:https://github.com/lanbeilyj/Accerlerated-C-plus-plus
7-0. Compile, execute, and test the programs in this chapter.
Ans:见Github。
7-1. Extend the program from §7.2/124 to produce its output sorted by occurrence count. That is, the output should group all the words that occur once, followed by those that occur twice, and so on.
Ans:见Github。
7-2. Extend the program in §4.2.3/64 to assign letter grades by ranges:
A 90-100 B 80-89.99... C 70-79.99... D 60-69.99... F < 60
The output should list how many students fall into each category.
Ans:见Github。
7-3. The cross-reference program from §7.3/126 could be improved: As it stands, if a word occurs more than once on the same input line, the program will report that line multiple times. Change the code so that it detects multiple occurrences of the same line number and inserts the line number only once.
Ans:见Github。
7-4. The output produced by the cross-reference program will be ungainly if the input file is large. Rewrite the program to break up the output if the lines get too long.
Ans:这里假设输出10列时就换行,程序见Github。
7-5. Reimplement the grammar program using a list
as the data structure in which we build the sentence.
Ans:用list替换vector,同时注意list不支持索引操作,故需要将使用索引部分改为使用迭代器,具体程序见Github。
7-6. Reimplement the gen_sentence
program using twovector
s: One will hold the fully unwound, generated sentence, and the other will hold the rules and will be used as a stack. Do not use any recursive calls.
Ans:在用堆栈保存规则时,由于语句生成的顺序要求为:the 名词短语 动词 位置,以及栈的先进后出特点,故规则是按照从右向左存储,具体程序见Github。
7-7. Change the driver for the cross-reference program so that it writesline
if there is only one line andline
s otherwise.
Ans:见Github。
7-8. Change the cross-reference program to find all the URLs in a file, and write all the lines on which each distinct URL occurs.
Ans:见Github。
7-9. (difficult) The implementation of nrand in §7.4.4/135 will not work for arguments greater thanRAND_MAX
. Usually, this restriction is no problem, becauseRAND_MAX
is often the largest possible integer anyway. Nevertheless, there are implementations under whichRAND_MAX
is much smaller than the largest possible integer. For example, it is not uncommon forRAND_MAX
to be 32767 (215 -1) and the largest possible integer to be 2147483647 (231 -1). Reimplementnrand
so that it works well for all values ofn
.
Ans:这题有点不太清楚,先是修改如下:(如果哪位觉得有问题可以把你的想法告诉我,非常感谢)
int nrand(int n) { if(n<=0) throw domain_error("Argument to nrand is out of range."); int r; if(n<RAND_MAX) { const int bucket_size=RAND_MAX/n; do { r=rand()/bucket_size; }while(r>=n); } else//n>=RAND_MAX { const int bucket_size=(n+rand())/RAND_MAX; do { r=rand()/bucket_size; }while(r>=n); } return r; }