练习 9.28: 编写函数,接受一个 forward_list<string>和两个string共三个参数。函数应在链表中查找第一个string,并将第二个string 插入到紧接着第一个string之后的位置。若第一个string未在链表中,则将第二个string插入到链表末尾
My Code:
#include<iostream>
#include<forward_list>
#include<string>
using namespace std;
//下面的第一个参数值得注意:
void insert_ (forward_list<string> &fl, string str1, string str2) {
auto prev = fl.before_begin();
auto curr = fl.begin();
while(curr != fl.end()) {
if (*curr == str1) {
fl.insert_after(prev, str2);
return;
} else {
prev = curr;
curr++;
}
}
fl.insert_after(prev, str2);
return;
}
int main()
{
forward_list<string> flst = {"My", "Is", "Otsan"};
string str1("Is"), str2("Name"), str3("!");
insert_(flst, str1, str2);
insert_(flst, str3, str3);
for (auto &a : flst)
cout << a << " ";
cout << endl;
return 0;
}