C++primer 9.2.1節練習

來源:互聯網
上載者:User

標籤:ons   ++   int   tor   hat   cto   clu   順序   runtime   

練習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         else26             ++(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         try24         {25             if (*it == a)26                 return &it;27             else28                 ++(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)

C++primer 9.2.1節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.