}/************
iostream iterator
STL定义了供输入及输出的iostream iterator类,称为
istream_iterator和ostream_iterator,分别支持单一
型别的元素的读取和写入。
使用方法:
1.包含头文件:
#include <iterator>
using namespace std;
2.像使用其他iterator一样使用istream_iterator和
ostream_iterator。如:
使用一对“连接至标准输入”的iterator用于标示元素范围:
// 将is定义为一个“连接至标准输入装置”的istream_iterator
istream_iterator<string> is(cin);
// 定义istream_iterator时不为它指定istream对象,它即代表
// 了end-of-file。
istream_iterator<string> eof;
ostream_iterator<string> os(cout, " ");
除了“连接至标准输入”外,还可以连接至其他设备,如文件:
#include <fstream>
using namespace std;
ifstream in_file("in.txt");
ofstream out_file("in.txt");
if ( !in_file || !out_file )
{
cerr << "failed to open the necessary file! /n";
return -1;
}
istream_iterator<string> is(in_file);
istream_iterator<string> eof;
ostream_iterator<string> os(out_file, " ");
*************/
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
// 1. 标准输入输出操作。
istream_iterator<string> is(cin);
istream_iterator<string> eof;
vector<string> text;
// 将标准输入的内容复制至text中。
// 由于使用的是vector,故使用back_inserter()
copy(is, eof, back_inserter(text));
// do something.
sort(text.begin(), text.end());
// 输出至标准输出。
ostream_iterator<string> os(cout, " ");
copy(text.begin(), text.end(), os);
// 2. 非标准输入输出操作:文件读写操作。
ifstream in_file("in.txt");
ofstream out_file("in.txt");
if ( !in_file || !out_file )
{
cerr << "failed to open the necessary file! /n";
return -1;
}
istream_iterator<string> is2(in_file);
istream_iterator<string> eof2;
vector<string> text2;
copy(is2, eof2, back_inserter(text2));
sort(text2.begin(), text2.end());
ostream_iterator<string> os2(out_file, " ");
copy(text2.begin(), text2.end(), os2);
return 0;
}