c++ primer p314页 练习9.28题解决方法,但不是很完善

来源:互联网 发布:网络安全 知乎 编辑:程序博客网 时间:2024/05/17 18:03

编写函数,接受一个forward_list和两个string共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置.若第一个string未在链表中,则将第二个string插入到链表中。


#include<iostream>
#include<forward_list>
#include<string>
using namespace std;


//forward_list的迭代器不支持--,关系运算符操作


void practise(forward_list<string> &v1, string s1, string s2) //这里必须传引用!!
{
//for (auto  &i:v1)
//if (s1==i)   需要使用迭代器
auto fl = v1.before_begin();
auto fl1 = v1.begin();
auto fl2 = v1.end();
cout << *fl1 << endl;
if (*fl1 == s1)
{
v1.insert_after(fl1, s2);
}
auto p = fl1, q = ++fl1;
cout<<*fl1<<endl;
for (; q != fl2; ++q, ++p)
{

if (*q == s1)
{
v1.insert_after(q, s2);
}

}
v1.insert_after(p, s2);
// 这样可以用来找forward_list的尾元素
/*auto p = fl1;
auto q = ++fl1;
for (; q != fl2; ++q)
p++;
v1.insert_after(p, s2);
*/
}
int main()
{
forward_list<string> fl = { "xia", "xi", "x", "xii", "xia" };
practise(fl, "xia", "w");
for (auto &i : fl)
cout << i << " ";


}


问题在于,没有同时实现!也就是说,当s1能被找到时会插入s2,同时末尾也得插入s2;s1 未找到时,末尾也会插入s2。。逻辑有些问题,期待各位大侠指点。

0 0
原创粉丝点击