首页 > 代码库 > C++primer 9.3.4节练习
C++primer 9.3.4节练习
练习9.27
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 #include <forward_list> 8 9 using namespace std; 10 11 12 int main() 13 { 14 forward_list<int> flist{ 1,2,3,4,5,6,7 }; 15 auto prev = flist.before_begin(); 16 auto curr = flist.begin(); 17 while (curr != flist.end()) 18 { 19 if (*curr % 2) 20 { 21 curr = flist.erase_after(prev); 22 } 23 else 24 { 25 prev = curr; 26 ++curr; 27 } 28 } 29 for (auto c : flist) 30 cout << c << endl; 31 system("pause"); 32 return 0; 33 }
练习9.28
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <deque> 5 #include <string> 6 #include <iterator> 7 #include <forward_list> 8 9 using namespace std; 10 11 void checkAndInsert(forward_list<string> &str, string str1, string str2); 12 13 int main() 14 { 15 forward_list<string> s{ "qwer","asdf", "ghjk","zxcv" }; 16 string s1{ "tyui" }; 17 string s2{ "haha" }; 18 checkAndInsert(s, s1, s2); 19 for (auto c : s) 20 cout << c << endl; 21 system("pause"); 22 return 0; 23 } 24 25 void checkAndInsert(forward_list<string> &str, string str1, string str2) 26 { 27 auto prev = str.before_begin(); 28 auto curr = str.begin(); 29 auto last = str.end(); 30 int count = 0; 31 while (curr != last) 32 { 33 if (*curr == str1) 34 { 35 prev = curr; 36 curr = str.insert_after(curr, str2); 37 ++count; 38 } 39 else 40 { 41 prev = curr; 42 ++curr; 43 } 44 if (!count) 45 { 46 if (curr == last) 47 str.insert_after(prev, str2); 48 } 49 } 50 }
C++primer 9.3.4节练习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。