C++primer 9.2.1节练习

练习9.3

迭代器begin和end必须指向相同的容器,end可以与begin指向相同的位置,但不能指向begin之前的位置;

练习9.4

 1 #include <iostream>
 2 #include <fstream>
 3 #include <sstream>
 4 #include <vector>
 5 #include <iterator>
 6 
 7 using namespace std;
 8 
 9 bool checkValue(vector<int>::iterator it, vector<int>::iterator it1, int a);
10 
11 int main()
12 {
13     vector<int> num{ 1,2,3,4,5,6 };
14     cout << checkValue(num.begin(), num.end(), 7) << endl;
15     system("pause");
16     return 0;
17 }
18 
19 bool checkValue(vector<int>::iterator it, vector<int>::iterator it1, int a)
20 {
21     while (it != it1)
22     {
23         if (*it == a)
24             return true;
25         else
26             ++(it);
27     }
28     return false;
29 }

练习9.5

 1 #include <iostream>
 2 #include <fstream>
 3 #include <sstream>
 4 #include <vector>
 5 #include <iterator>
 6 
 7 using namespace std;
 8 
 9 const vector<int>::iterator *checkValue (vector<int>::iterator it, vector<int>::iterator it1, int a);
10 
11 int main()
12 {
13     vector<int> num{ 1,2,3,4,5,6 };
14     cout << (checkValue(num.begin(), num.end(), 7)) << endl;
15     system("pause");
16     return 0;
17 }
18 
19  const vector<int>::iterator *checkValue (vector<int>::iterator it, vector<int>::iterator it1, int a)
20 {
21     while (it != it1)
22     {
23         try
24         {
25             if (*it == a)
26                 return &it;
27             else
28                 ++(it);
29             if (it == it1)
30                 throw runtime_error("error");
31         }
32         catch (runtime_error err) {
33             cout << err.what() << endl;
34         }
35     }
36     return &it1;
37 }

利用抛出异常的方法来处理未找到定值的情况;

练习9.6

迭代器支持的算术运算不能用于list容器,因为list容器不是按照顺序存储的,他是个双向链表;

改成while(iter1 != iter2)

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7326968.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
c primer 15.9作业是关于异常处理的内容。在这一中,主要介绍了C语言中的错误处理机制和异常处理方式。 异常处理是一种程序设计中的重要思想,它允许应对出现的各种错误或异常情况,从而增加程序的健壮性和可靠性。C语言中的异常处理主要通过使用错误码和错误处理函数来实现。 在进行异常处理时,通常需要先定义一些错误码,用于标识可能出现的异常情况。C语言提供了一些标准的错误码,如errno.h头文件中定义的错误码,还可以根据需要自定义错误码。 接下来,我们需要在程序中合适的位置进行错误检测并进行异常处理。可以使用if语句或者switch语句等条件语句来检测错误码,并根据不同的错误码执行相应的错误处理代码。 错误处理代码的内容可以根据具体情况而定,它可以是打印错误信息、修复错误、返回错误码等操作。在处理完异常后,可以继续执行后续的程序逻辑,或者返回到调用处继续处理。 除了使用错误码和错误处理函数进行异常处理外,C语言还提供了一种特殊的异常处理方式,即信号处理。信号处理是通过捕捉和处理操作系统发送的信号来实现的,通过注册信号处理函数,可以在程序遇到特定信号时执行相应的处理代码。 总之,C语言中的异常处理是一种重要的错误处理机制,可以提高程序的可靠性和健壮性。通过定义错误码、错误处理函数和信号处理,可以有效地捕捉和处理各种异常情况。在编写C程序时,合理地使用异常处理机制是至关重要的。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值