第十章 10.2.2节练习

练习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执行完成后,对容器也没有任何改变。

能改变其中元素的是其返回的迭代器指针。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值