码迷,mamicode.com
首页 > 编程语言 > 详细

C++primer 9.2.7节练习

时间:2017-08-09 22:18:05      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:pac   prim   定义   ...   names   运算符   name   else   pre   

练习9.15

 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <iterator>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     vector<int> v1{ 1, 3, 5, 7, 9 };
11     vector<int> v2{ 1,3,9 };
12     vector<int> v3{ 1,3,5,7 };
13     vector<int> v4{ 1,3,5,7,9 };
14     if (v1 < v2)
15         cout << true << endl;
16     else
17         cout << false << endl;
18     system("pause");
19     return 0;
20 }

 

练习9.16

 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <iterator>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     vector<int> v1{ 1, 3, 5, 7, 9 };
11     list<int> v2{ 1,3,9 };
12     auto beg = v1.begin();
13     auto last = v1.end();
14     auto beg1 = v2.begin();
15     auto last1 = v2.end();
16     for (; beg != last && beg1 != last1; ++beg, ++beg1)
17     {
18         if (*beg > *beg1)
19             cout << "true" << endl;
20         else if (*beg == *beg1)
21             cout << "equal" << endl;
22         else
23             cout << "false" << endl;
24     }
25     system("pause");
26     return 0;
27 }

 网上答案利用拷贝初始化在进行同类型容器同类型元素的比较,个人觉得比我的好。

 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 using namespace std;
 5 
 6 bool compare_vector(vector<int> vec1, vector<int> vec2, int a, int b)//输入两个参数,a,b表示访问的下标,利用了vector<int> 随机访问的特性 
 7 {
 8    if(a <= vec1.size() && b <= vec2.size())
 9    {
10       if(vec1[a] == vec2[b])
11          return true;
12       else 
13          return false;
14    }    
15    else 
16         return false;
17 } 
18 
19 bool compare_list_vector(list<int> li, vector<int> vec, int a, int b)
20 {
21     vector<int> temp(li.begin(), li.end()); 
22     //利用拷贝初始化,先将li的内容拷贝一个vector<int> temp,然后就和上面一样了。 
23     if(a <= temp.size() && b <= vec.size())
24     {
25         if(temp[a] == vec[b])
26             return true;
27         else 
28             return false;
29     }
30     else
31         return false;
32  } 
33 
34 int main()
35 {
36     vector<int> vec1 = {1,2,3,4,5,6};
37     vector<int> vec2 = {1,2,3,4,5};
38     list<int> li = {1,2,3,4,5,6};
39     if(compare_list_vector(li,vec1,2,2))
40         cout << "Equal!!!" << endl;
41     else
42         cout << "Not Equal..." << endl;
43     return 0;
44 }

 

练习9.17

c1和c2的容器类型必须相同,且容器中的元素类型也必须相同,还有容器中的元素类型必须要定义了相应的比较运算符

C++primer 9.2.7节练习

标签:pac   prim   定义   ...   names   运算符   name   else   pre   

原文地址:http://www.cnblogs.com/wuyinfenghappy/p/7327840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!