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();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 }

 

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7341102.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值