练习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();30 int count = 0; 31 while (curr != str.end()) 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 == str.end()) 47 str.insert_after(prev, str2); 48 } 49 } 50 }