9.28 編寫函式,接受一個forward_list<string>和兩個string共三個引數。函式應在連結串列中查詢第一個string,並將第二個string插入到緊接著第一個string之後的位置。若第一個string未在連結串列中,則將第二個string插入到連結串列末尾。
#include<iostream> #include<forward_list> #include<string> using namespace std; void insert(forward_list<string> &flist,string s1,string s2) { auto prev=flist.before_begin(); auto curr=flist.begin(); while(curr!=flist.end()) { if(*curr==s1) { flist.insert_after(curr,s2); break; } else { prev=curr; ++curr; } } if(curr==flist.end()) flist.insert_after(prev,s2); } int main() { forward_list<string> flist={"a","b","c","d","e"}; insert(flist,"f","b"); for(auto f:flist) cout<<f<<" "; cout<<endl; return 0; }
結果如下: