练习10.6:编写程序,使用fill_n,将一个序列中的int值都设置为0。
答:见练习10.6.cpp
练习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());
答:lst中push_back(i)后,长度变化,而vec是空的,长度和lst不一样,传递给copy的目的序列至少要包含与输入序列一样多的元素,这一点很重要。修改为vector<int> vec(10);
输入小于等于10个数。
(b)
vector<int> vec;//修改为vector<int> vec(10);
vec.reserve(10);//去掉
Fill_n(vec.begin(),10,0);
答:vec.reserve(10)只是给vec预分配了10个空间,实际vec还是空的,因此程序不执行。
见练习10.7.cpp
练习10.8:本节提到过,标准库算法不会改变它们所操纵容器的大小。为什么使用back_inserter不会使这一断言失效。
答:back_inserter是定义在头文件iterator中的函数,说到底它只是用来在算法执行过程中,可能需要添加元素的情况,添加元素这种粗活,并不是算法干的,算法只是要求这一过程,真正执行这一过程的是一个迭代器。书上说的很清楚,所以这一断言不会失效。
练习10.6
/*
*练习10.6
*2015/8/12
*问题描述:练习10.6:编写程序,使用fill_n,将一个序列中的int值都设置为0。
*说明:fill_n的使用
*作者:Nick Feng
* 邮箱:nickgreen23@163.com
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int value;
vector<int> vec;
cout << "please input numbers , ending of Enter and ctrl+C " << endl;
while(cin >> value)
vec.push_back(value);
cout << "before fill_n operation: " << endl;
for(auto i = 0; i != vec.size(); ++i)
cout << vec[i] << " ";
cout << endl;
fill_n(vec.begin(),vec.size(),0);
cout << "after fill_n operation: " << endl;
for(auto i = 0; i != vec.size(); ++i)
cout << vec[i] << " ";
cout << endl;
return 0;
}
练习10.7
/*
*练习10.7
*2015/8/12
*问题描述:练习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);
* Fill_n(vec.begin(),10,0);
*说明:fill_n的使用
*作者:Nick Feng
* 邮箱:nickgreen23@163.com
*/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vec(10);
list<int> lst;
int i;
while(cin >> i)
lst.push_back(i);
copy(lst.cbegin(),lst.cend(),vec.begin());
for(auto i = 0; i != vec.size(); ++i)
cout << vec[i] << " ";
cout << endl;
vector<int> vec1(10);
//vec1.reserve(10);
//cout << vec1.size();
fill_n(vec1.begin(),10,0);
for(auto i = 0; i != vec1.size(); ++i)
cout << vec1[i] << " ";
cout << endl;
return 0;
}