首页 > 代码库 > forward_list例子

forward_list例子

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;}

结果如下: