首页 > 代码库 > C++primer 9.3.1节练习
C++primer 9.3.1节练习
练习9.18
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 8 using namespace std; 9 10 int main() 11 { 12 deque<string> de; 13 string word; 14 while (cin >> word) 15 { 16 de.push_back(word); 17 } 18 for (auto it = de.begin(); it != de.end(); ++it) 19 cout << *it << endl; 20 system("pause"); 21 return 0; 22 }
练习9.19
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 8 using namespace std; 9 10 int main() 11 { 12 list<string> de; 13 string word; 14 while (cin >> word) 15 { 16 de.push_back(word); 17 } 18 for (auto it = de.begin(); it != de.end(); ++it) 19 cout << *it << endl; 20 system("pause"); 21 return 0; 22 }
练习9.20
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 8 using namespace std; 9 10 void print(const deque<int> de); 11 12 int main() 13 { 14 list<int> num; 15 num.insert(num.begin(), { 1,2,3,4,5,6,7,8,9,10 }); 16 deque<int> num1; 17 deque<int> num2; 18 for (auto it = num.begin(); it != num.end(); ++it) 19 { 20 if ((*it) % 2 == 0) 21 num1.push_back(*it); 22 else 23 num2.push_back(*it); 24 } 25 print(num1); 26 cout << endl; 27 print(num2); 28 system("pause"); 29 return 0; 30 } 31 32 void print(const deque<int> de) 33 { 34 for (auto c : de) 35 cout << c << endl; 36 }
练习9.21
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 8 using namespace std; 9 10 11 int main() 12 { 13 vector<string> lst; 14 string word; 15 auto iter = lst.end(); 16 while (cin >> word) 17 { 18 iter = lst.insert(iter, word); 19 } 20 for (auto c : lst) 21 cout << c << endl; 22 system("pause"); 23 return 0; 24 }
练习9.22
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 8 using namespace std; 9 10 11 int main() 12 { 13 int some_val = 1; 14 vector<int> iv{ 1,2,3,4,5,6,7,8,9,10 }; 15 auto i = iv.size(); 16 vector<int>::iterator iter = iv.begin(), 17 mid = iv.begin() + iv.size() / 2; 18 while (iter != mid) 19 { 20 if (*iter == some_val) 21 { 22 iter = iv.insert(iter, 2 * some_val); 23 iter = iter + 2; 24 mid = iv.begin() + i / 2; 25 } 26 else 27 ++iter; 28 } 29 for (auto c : iv) 30 cout << c << endl; 31 system("pause"); 32 return 0; 33 }
一个是该循环是个死循环,iter永远不会不等于mid,第二点很重要,自己在做题时有遗漏,向一个vector、string、deque插入元素会使所有指向容器的迭代器、引用和指针失效。
C++primer 9.3.1节练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。