练习 9.28:编写函数,接受一个 forwar_list<string> 和两个 string 共三个参数。函数应在链表中查找第一个 string,并将第二个 string 插入到紧接着第一个 string 之后的位置。若第一个 string 未在链表中,则将第二个 string 插入到链表末尾。
#include <iostream>
#include <forward_list>
#include <string>
using std::cout;
using std::forward_list;
using std::string;
/*函数形参列表中,forward_list<string> &flst中的"&"千万不能少,没有"&",则程序修改的是副本,
有"&"时,修改的才是原文件。*/
void lookup(forward_list<string> &flst, string s1, string s2)
{
auto prev = flst.before_begin();
auto curr = flst.begin();
int string_num = 0;
while (curr != flst.end())
{
if (*curr == s1)
{
++string_num;
curr = flst.insert_after(curr, s2);
prev = curr;
++curr;
}
else
{
prev = curr;
++curr;
}
}
if (string_num == 0)
flst.insert_after(prev, s2);
}
int main()
{
forward_list<string> rflst = {"笑一下:", " 再", "笑一下:"};
string rs1 = "笑一下:", rs2 = "呵呵~";
lookup(rflst, rs1, rs2);
cout << "更新后的rflst是:";
for (const auto &s : rflst)
cout << s;
return 0;
}