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

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

2014-10-20 23:58 429 查看
说明:从本章开始除了思路分析或者不需要代码的题目,其他涉及代码的题目就不再这里帖出代码了(重复和费时间),源代码全部放在了GitHub我的Github地址:https://github.com/lanbeilyj/Accerlerated-C-plus-plus

6-0.    Compile, execute, and test the programs in this chapter.

见github。

6-1.    Reimplement the
frame
and
hcat
operations from §5.8.1/93 and §5.8.3/94 to use iterators.

见github。

6-2.    Write a program to test the
find_urls
function.

见github。

6-3.    What does this program fragment do?

vector<int> u(10, 100);
vector<int> v;
copy(u.begin(), u.end(), v.begin());


Write a program that contains this fragment, and compile and execute it.

Ans:本题作者的目的是初始化一个含有10个值为100的容器,然后将该容器的每个值copy给另一个新的空容器;但是作者的copy算法调用是错误的,因为v为空所以v.begin()是一个并不存在的元素,对其复制的结果是未定义,提示segment error!如本书所介绍,copy算法这么设计是区分复制和扩展容易的概念。当v含有k个元素时则只是复制k个u中的值到v中,而u中多余的值并不能复制;当第三个参数为迭代器适配器时,则copy会将u中所有元素全部复制给v,若v的容量不足则会扩展以容纳u中的元素。

所以应该修改为:copy(u.begin(),u.end(),back_inserter(v));

6-4.   Correct the program you wrote in the previous exercise to copy from
u
into
v
. There are at least two possible ways to correct the program. Implement both, and describe the relative advantages and disadvantages
of each approach.

Ans:1、vector<int> v(u.begin(),u.end());

          2、vector<int> v; v=u;

第二种等价于首先将v容器清空即v.erase(v.begin(),v.end()),然后再插入v.insert(u.begin(),u.end(),v.begin());而第一种实质也是insert故相比较第一种优于第二种,但是对这个例子并不明显。

6-5.   Write an analysis function to call
optimistic_median
.

见github。

6-6.   Note that the function from the previous exercise and the functions from §6.2.2/113 and §6.2.3/115 do the same task. Merge these three analysis functions into a single function.

见github。

6-7.   The portion of the grading analysis program from §6.2.1/110 that read and classified student records depending on whether they did (or did not) do all the homework is similar to the problem we solved in
extract_fails
.
Write a function to handle this subproblem.

见github。

6-8.   Write a single function that can be used to classify students based on criteria of your choice. Test this function by using it in place of the
extract_fails
program, and use it in the program to analyze student grades.

Ans:感觉这题意义不大,只是根据条件分类来push_back,然后就是分别调用,为了让读者更熟悉这种算法吧。见github。

6-9.   Use a library algorithm to concatenate all the elements of a
vector<string>
.

Ans:需要连接字符串故想到用库算法accumulate(begin,end,string),第三个参数表示一字符串我们将其表示为:string s=accumulate(v.begin(),v.end(),string(""));具体代码见github。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐