练习9.27:编写程序,查找并删除forward_list<int>
中的奇数元素。
答: 见练习9.27.cpp
练习9.28:编写程序,接受一个forward_list<string>
和 两个string共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。若第一个string未在链表中,则将第二个string插入到链表末尾。
答:见练习9.28.cpp
练习9.27
/*
*练习9.27
*2015/8/2
*问题描述:练习9.27:编写程序,查找并删除forward_list<int>中的奇数元素。
*功能:forward_list的使用
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <forward_list>
using namespace std;
int main()
{
forward_list<int> flst = {1,2,3,4,5,6,7,8,9};
auto prev = flst.before_begin();
auto curr = flst.begin();
while(curr != flst.end())
{
if(*curr % 2)
curr = flst.erase_after(prev);
else
{
prev = curr;
++curr;
}
}
for(auto it = flst.begin(); it != flst.end(); ++it)
cout << *it << " ";
cout << endl;
return 0;
}
练习9.28
/*
*练习9.28
*2015/6/15
*问题描述:练习9.28:编写程序,接受一个forward_list<string> 和 两个string共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。若第一个string未在链表中,则将第二个string插入到链表末尾。
*说明:forward_list末尾元素,需要遍历得到,不能直接取得,另外注意,引用类型,和普通函数的区别,值的变化
*编写了三个函数,
*take_last_value(),取到尾末迭代器, 返回尾末迭代器
*look_value();//如果有这个string存在,返回那个位置的迭代器,否则,返回尾末迭代器
*complace();//题目要求的函数,如果直接在这里面写循环,会造成,假如找到了匹配的string,循环还是会往后遍历,在尾末加string2,因此,需要借助look_value的帮助进行定位
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*
*/
#include <iostream>
#include <forward_list>
#include <string>
using namespace std;
forward_list<string>::iterator take_last_value(forward_list<string> &flst) //小函数,取得尾末迭代器,注意引用
{
forward_list<string>::iterator curr = flst.begin();
forward_list<string>::iterator it = flst.begin();
while(1)
{
curr = it++;//it++和++it是有区别的
if(it == flst.end())
break;
}
return curr;
}
forward_list<string>::iterator look_value(forward_list<string> &flst,string str)
//小函数,找准是否有str的迭代器,如果有,返回找到的迭代器,没有,返回尾末迭代器
{
forward_list<string>::iterator it = flst.begin();
while(it != flst.end())
{
if(*it == str) //找到了,退出循环
{
return it;
break;
}
else
++it;
}
return take_last_value(flst); //其他情况,返回尾末迭代器
}
void complace(forward_list<string> &flst, string str1, string str2)
//题目要求的函数
{
forward_list<string>::iterator it;
it = look_value(flst,str1); //调用第二个函数
flst.insert_after(it,str2);//相应位置插入
}
void print(forward_list<string> flst)
{
for(auto it = flst.begin(); it != flst.end();++it)
cout << *it << " ";
cout << endl;
}
int main()
{
forward_list<string> flst = {"This","is","a","test!"};
complace(flst,"a","good");
print(flst);
complace(flst,"f","!!");
//因为flst是被引用的,因此,这里的flst是上面处理后的flst
print(flst);
return 0;
}