C++ primer 第五版 中文版 9.3.4 节练习
练习 9.27:编写程序,查找并删除forward_list<int>中的奇数元素。
答:
/*
编写程序,查找并删除forward_list<int>中的奇数元素。
*/
#include <iostream>
#include <forward_list>
using std::cout;
using std::endl;
using std::forward_list;
int main()
{
forward_list<int> flist{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 };
cout << "删除奇数元素前flist中的元素内容为:";
for (const auto &a : flist)
cout << a << " ";
cout << endl;
auto prev = flist.before_begin();
auto curr = flist.begin();
while (curr != flist.end())
{
if (*curr % 2)
{
curr = flist.erase_after(prev);
}
else
{
prev = curr;
++curr;
}
}
cout << "删除奇数元素后flist中的元素内容为:";
for (const auto &a : flist)
cout << a << " ";
cout << endl;
return 0;
}
执行结果:
练习 9.28:编写函数,接受一个forward_list<string> 和两个 string 共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。若第一个string未在链表中,刚将第二个string 插入到链表末尾。
答:
/*
编写函数,接受一个forward_list<string> 和两个 string 共三个参数。
函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。
若第一个string未在链表中,刚将第二个string 插入到链表末尾。
*/
#include <iostream>
#include <forward_list>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::forward_list;
using std::string;
//在单向链表flist中查找findword,并将 insertword插入到找到的findword之后的位置。若findword未在链表中,则将insertword 插入到链表末尾。
void find_or_insert(forward_list<string> &flist, const string &findword, const string &insertword)
{
auto tmpiter = flist.before_begin();
auto curriter = flist.begin();
bool flag = false;
while (curriter != flist.end())
{
if (*curriter == findword)
{
flag = true;
curriter = flist.insert_after(curriter, insertword);
}
else
{
tmpiter = curriter;
++curriter;
}
}
if (!flag)
flist.insert_after(tmpiter, insertword);
}
int main()
{
forward_list<string> strflist = { "Hello", "C++", "I", "got", "you" ,"Hello","Primer"};
cout << "list<string>容器内的元素为:";
for (const auto &a : strflist)
cout << a << " ";
cout << endl;
string findkeyword, insertkeyword;
cout << "请输入要查找的关键词和要插入的关键词:";
cin >> findkeyword >> insertkeyword;
find_or_insert(strflist, findkeyword, insertkeyword);
cout << "插入关键词后list<string>容器内的元素为:";
for (const auto &a : strflist)
cout << a << " ";
cout << endl;
return 0;
}
执行结果: