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)

posted @ 2017-08-09 18:22  五月份小姐  阅读(247)  评论(0编辑  收藏  举报