c++ primer p314頁 練習9.28題解決方法,但不是很完善

編寫函數,接受一個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。。邏輯有些問題,期待各位大俠指點。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章