且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

linux下练习 c++ 输入输出迭代器

更新时间:2022-05-04 19:08:22

iterator.cpp

/*

迭代器

输入:可读,不一定可改值

输出:可改,不一定可读值

前向:可读可改

双向:支持 --

随机:支持--、+n、-n、下标访问

*/

#include<iterator>

#include<iostream>

using namespace std;

#include<algorithm>

#include<vector>

#include "print.h"

#include<fstream>

int main()

{

	//输入迭代

	istream_iterator<int> in(cin);//输入流cin,也可以是文件输入流

	istream_iterator<int> end;

	vector<int> vi;

	copy(in,end,back_inserter(vi));//一直输入,按ctrl+D结束

	print(vi.begin(),vi.end());

	//输出迭代

	ofstream fo("out.txt");

	ostream_iterator<int> o(cout,",");

	ostream_iterator<int> ofile(fo," ");

	copy(vi.begin(),vi.end(),o);

	copy(vi.begin(),vi.end(),ofile);

	fo.close();

	cout<<endl;

	

}


print.h

//print.h

#include <iostream>

using namespace std;

#ifndef print_fun

#define print_fun

template<typename T>

///显示序列数据

void print(T b,T e,char c=' ')

{

	bool isExit=false;

	while (b!=e)

	{

		cout<<*b++<<c;

		isExit=true;

	}

	if(isExit) cout<<endl;



}

template<typename K,typename V>

ostream& operator<<(ostream& o,const pair<K,V>& p)//重载输出map类型元素

{

	return o<<p.first<<':'<<p.second;

}

#endif


 

结果:

linux下练习 c++ 输入输出迭代器