C++:forward_list尾部添加元素

“棘手”的问题

请使用C++11新标准编译运行.[此源码并非一个完美的解决方案.仅供测试学习.]

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

从前面向forward_list插入数据很简单,而从尾部插入数据则难度很大。目前这个解决方案解决了题目的问题,但明显不是最好的解决方案。

C++.
image-2048

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*************************************************************************
    > File Name: test.9.28.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2014年05月16日 星期五 18时42分53秒
 ************************************************************************/

#include<iostream>
#include<forward_list>
#include<vector>
#include<iterator>
using namespace std;


//只用作输出.
void out(const forward_list<string> &lst,const string title)
{
    cout << title << endl;
    for(forward_list<string>::const_iterator it=lst.cbegin();it!=lst.cend();++it)
    {
        cout << *it << endl;
    }
    cout << "----------------------" << endl;
}

void insertFor(forward_list<string> &lst,string name1,string name2)
{
   
    /*
     * 实现流程[当没有找到name1时,将name2添加到最后面.]:
     * 1.先将原有数据保存到vector[可逆序输出]
     * 2.用name2替换原有的内容
     * 3.逆序将vector中的内容,添加到forward_list中.
     *----------------------------------------------
     * 当有name1的时候,直接添加完跳出循环即完成.
     */
    vector<string> vec(lst.begin(),lst.end());//拷贝lst中的值.
    out(lst,"输出未改变前的forward_list:");//输出刚才获取的值.
    for(forward_list<string>::iterator it=lst.begin();it!=lst.end();++it)
    {//用于查找,替换.
        if((*it)==name1)//forward_list里面有name1.
        {
            lst.insert_after(it,name2);//插入到当前位置之后的位置.
            break;//找到加入值之后就可以退出循环了.
        }
        else
        {//没找到name1的值,用name2替换原来的值.
            lst.assign({name2});//替换.
            for(vector<string>::reverse_iterator itsa=vec.rbegin();itsa!=vec.rend();++itsa)
            {
                lst.push_front(*itsa);//将已经被替换掉的逆序元素添加回去.
            }
        }
    }
    out(lst,"输出已经改变后的值");
   
}


int main()
{
    forward_list<string> lst = {"test","demo","java","cpp","c","hello"};
    string name1 = "test",name2="slkjsd";//模式1
    //string name1 = "testssa",name2="slkjsd";//模式2
    insertFor(lst,name1,name2);//查找及替换.
    return 0;
}

《C++:forward_list尾部添加元素》上有1条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据