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

说明:从本章开始除了思路分析或者不需要代码的题目,其他涉及代码的题目就不再这里帖出代码了(重复和费时间),源代码全部放在了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 fromu intov. 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 inextract_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 theextract_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 avector<string>.

Ans:需要连接字符串故想到用库算法accumulate(begin,end,string),第三个参数表示一字符串我们将其表示为:string s=accumulate(v.begin(),v.end(),string(""));具体代码见github。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值