金海佳学C++primer 练习9.28

forward_list中查找str1并将str2插到后面

Practice 9.28

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
#include <iterator>
#include <cmath>
#include <cstring>
#include <forward_list>
using namespace std;

void print(forward_list<string> flst) {
    for(auto i : flst) {
        cout << i << " ";
    }
    cout << endl;
}
// str1 perhaps is equal to str2
void find_str1_insert_str2(forward_list<string> flst, string str1, string str2) {
    auto cur = flst.begin();
    while(1) {
        if(cur == flst.end()) {
            cout << "Find nothing!" << endl;
            return;
        }
        if(*cur == str1) {
            cur = flst.insert_after(cur, str2);
            break;
        }
        cur++;
    }
    cout << "Done!" << endl;
    print(flst);
    return;
}

int main() {
    forward_list<string> flst = {"jin", "hai", "jia"};
    /* test 1 */
    cout << "test1: find hai insert ding" << endl;
    find_str1_insert_str2(flst, "hai", "ding");
    /* test 2 */
    cout << "test2: find hai insert hai" << endl;
    find_str1_insert_str2(flst, "hai", "hai");
    /* test 3 */
    cout << "test3: find wang insert meng" << endl;
    find_str1_insert_str2(flst, "wang", "meng");
    /* test 4 */
    cout << "test4: find jia insert ding" << endl; 
    find_str1_insert_str2(flst, "jia", "ding");
    return 0;
}

Output

test1: find hai insert ding
Done!
jin hai ding jia 
test2: find hai insert hai
Done!
jin hai hai jia 
test3: find wang insert meng
Find nothing!
test4: find jia insert ding
Done!
jin hai jia ding 

Circumstances? I make circumstances!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值