C++primer 9.2.7節練習

來源:互聯網
上載者:User

標籤: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     else17         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         else23             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     else31         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     else42         cout << "Not Equal..." << endl;43     return 0;44 }

 

練習9.17

c1和c2的容器類型必須相同,且容器中的元素類型也必須相同,還有容器中的元素類型必須要定義了相應的比較子

C++primer 9.2.7節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.