C++代码编程学习:泛型编程风格——iterator学习三(Essential C++ 第三章)

C++中泛型编程风格------iterator学习,挺有难度,概念很抽象,这里主要把一些知识点和习题给过一遍!

一、前言

C++中泛型编程风格------iterator学习(Essential C++ 第三章)。

二、例题

-P225 练习 3.4

编写一个程序,利用istream iterator 从标准输人设备读取一连串整数。利用ostreamiterator 将其中的奇数写至某个文件,每个数值皆以空格分隔。再利用ostream iterator 将偶数写到另一个文件,每个数值单独放在一行中。

cpp 复制代码
class even_elem {
public:
	bool operator()(int elem)
	{
		return elem % 2 ? false : true;
	}
};


int main()
{

	vector<int> input;

	// 输入需要判断的数组
	istream_iterator<int> in(cin), eos;

	// 把需要判断的数组再赋值给input
	copy(in, eos, back_inserter(input));

	vector<int>::iterator division = partition(input.begin(), input.end(), even_elem());

	//1) 简单调试
	ostream_iterator<int> evenFile(cout, " ");
	ostream_iterator<int> oddFile(cout, " ");

	// 这个copy用的太棒了,从input头部读到division为偶数,从division读到input.end()为奇数
	copy(input.begin(), division, evenFile);
	cout << endl;
	copy(division, input.end(), oddFile);

	//2) 保存成为文件
	ofstream even_file("C:\\desktop\\even_file");
	ofstream odd_file("C:\\desktop\\odd_file");

	if (!even_file || !odd_file)
	{
		cerr << "Essential file do not exist!\n";
		return -1;
	}

	// 绑定文件关系
	ostream_iterator<int> even_iter(even_file, "\n"), odd_iter(odd_file, "\n");

	copy(input.begin(), division, even_iter);
	copy(division, input.end(), odd_iter);

}
  • 这道题非常的赞哦,有三个非常重要的知识点:
  • 1)istream_iterator<int> in(cin), eos; ------ 该代码有效地节省了cin函数输入地冗杂,但是调试上需要注意,如果输入的是整数数组,需要在按下回车之后,输入其他类型的数据,如字符型的a,如下图所示。
  • 2)copy()函数的使用非常重要;
  • 3)ostream_iterator<int> even_iter(even_file, "\n"), odd_iter(odd_file, "\n"); 文件绑定也非常值得学习一下。

代码是在 visual studio 中编写的,该软件还是比较好用的,我安装的是2022专业版;

共勉!

相关推荐
醉暮天20 分钟前
4.25学习——文件上传之00截断
学习
酷爱码1 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼1 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!2 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ3 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics3 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
blackA_4 小时前
数据库MySQL学习——day4(更多查询操作与更新数据)
数据库·学习·mysql
yuanManGan5 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++
北极的企鹅885 小时前
XML内容解析成实体类
xml·java·开发语言
梁下轻语的秋缘5 小时前
每日c/c++题 备战蓝桥杯(P1049 [NOIP 2001 普及组] 装箱问题)
c语言·c++·学习·蓝桥杯