练习10.6:
编写程序,使用fill_n将一个序列中的int值都设置为0。
解答:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector<int> a(10, 1); // 注意这里容器不能为空,否则会出现未定义的事件
for (auto i : a){
cout << i << " ";
}
cout << endl;
fill_n(a.begin(), a.size(), 0);
for (auto i : a){
cout << i << " ";
}
cout << endl;
}
练习10.7:
下面程序是否有错误?如果有,请改正。
//(a)
vector<int> vec; list<int> lst; int i;
while (cin >> i)
lst.push_back(i);
copy(lst.cbegin(), lst.cend(), vec.begin());
//(b)
vector<int> vec;
vec.reserve(10); //参考9.4节,318页
fill_n(vec.begin(), 10, 0);
解答:
(a)这里vec是空容器,在copy函数中,需要对迭代器指针进行解引用的操作,这就会产生段错误。
修改如下:
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <iterator>
using namespace std;
int main(){
vector<int> vec;
list<int> lst; int i;
while (cin >> i)
lst.push_back(i);
copy(lst.cbegin(), lst.cend(), back_inserter(vec));
for (auto i : vec){
cout << i << " ";
}
cout << endl;
}
(b)这里的问题和(a)的差不多,在对指针解引用的时候发生段错误。
这里虽然使用它reserve为vec分配了10个元素的空间,但是在调试的时候我们会看到,size的值为0,capacity的值为10。
size表示vector中存入了多少个元素,capacity表示容器可以存储多少元素。
所以reserve函数的调用依旧解决不了任何问题。
修改如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector<int> vec(10, -1);
vec.reserve(10);
fill_n(vec.begin(), 10, 0);
for (auto i : vec){
cout << i << " ";
}
cout << endl;
}
练习10.8:
本节提到过,标准库算法不会改变它们所操作的容器的大小。为什么使用back_inserter不会使这一断言失效?
解答:
这道题,我感觉有些怪怪的。
虽然,back_inserter出现在这一节,但是其操作是与迭代器指针相关的。
并且,在back_inserter执行完成后,对容器也没有任何改变。
能改变其中元素的是其返回的迭代器指针。