例题:在链表中查找一个字符串,并插入另一个字符串

来源:互联网 发布:穿越小说软件下载 编辑:程序博客网 时间:2024/05/16 08:17

题目为C++ primer 9.28

#include <iostream> 
#include <string>
#include <forward_list>
using namespace std;
void Insert(forward_list<string> &lst, const string &a, const string &b);

int main()
{
forward_list<string> lst{ "nayeon","tzuyu","momo","taeyeon" };
string a = "nayeon";
string b = "2yeon";
Insert(lst, a, b);
for (auto it : lst)
cout << it << endl;
system("pause");
return 0;
}


void Insert(forward_list<string> &lst, const string &a, const string &b)
{
auto it = lst.begin();
auto it_begin = lst.before_begin();
while (it != lst.end())
{
if (*it == a)
{
lst.insert_after(it, b);
break;
}
it_begin++;
it++;
}
if (it == lst.end())
{

lst.insert_after(it_begin, b);
}
}

0 0