练习9.27:
编写程序,查找并删除forward_list<int>中的奇数元素。
解答:
这段程序在本节已经给出来了,不过,forward_list是单向链表,比较特殊,所以这段程序还是值得花点时间看看的。
#include <iostream>
#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 i : flst){
cout << i << " ";
}
cout << endl;
}
练习9.28:
编写函数,接受一个forward_list<string>和两个string共三个参数。函数应在链表中查找第一个string,并将第二个string插入到紧接着第一个string之后的位置。若第一个string未在链表中,则将第二个string插入到链表末尾。
解答:
#include <iostream>
#include <forward_list>
#include <string>
using namespace std;
void myFunc(forward_list<string>& flst, string str1, string str2){
auto perv = flst.before_begin();
auto curr = flst.begin();
while (curr != flst.end()){
if (*curr == str1){
flst.insert_after(curr, str2);
return;
}
perv = curr;
++curr;
}
flst.insert_after(perv, str2);
}
int main(){
forward_list<string> flist{ "apple", "melon", "pear", "banana" };
myFunc(flist, "pear", "watermelon");
for (auto i : flist){
cout << i << " ";
}
cout << endl;
myFunc(flist, "house", "pineapple");
for (auto i : flist){
cout << i << " ";
}
cout << endl;
}
练习9.29:
假定vec包含25个元素,那么vec.resize(100)会做什么?如果接下来调用vec.resize(10)会做什么?
解答:
和314页list描述相似的处理方式。
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> vec(25, 99);
cout << "Original vec vessel elements" << endl;
for (auto i : vec){
cout << i << " ";
}
cout << endl;
vec.resize(100);
cout << "Resize the vessel to 100, the elements" << endl;
for (auto i : vec){
cout << i << " ";
}
cout << endl;
vec.resize(25);
cout << "Resize the vessel to 25, the elements" << endl;
for (auto i : vec){
cout << i << " ";
}
cout << endl;
}
练习9.30:
接受单个参数的resize版本对元素类型有什么限制(如果有的话)?
解答:
限制能想到的只有一个。
【引用】如果容器保存对的是类类型元素,且resize想容器添加新元素,则我们必须提供初始值,或者元素类型必须提供一个默认构造函数。