您的位置:首页 > 编程语言 > C语言/C++

Accelerated C++:通过示例进行编程实践——练习解答(第7章)

2014-10-22 15:26 453 查看
我的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 two
vector
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 writes
line
if there is only one line and
line
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 than
RAND_MAX
. Usually, this restriction is no problem, because
RAND_MAX
is often the largest possible integer anyway. Nevertheless,
there are implementations under which
RAND_MAX
is much smaller than the largest possible integer. For example, it is not uncommon for
RAND_MAX
to be 32767 (215 -1) and the largest possible integer to be 2147483647 (231
-1). Reimplement
nrand
so that it works well for all values of
n
.


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐