首页 > STL编程 > STL stream iterator – 流迭代器

STL stream iterator – 流迭代器

STL流迭代器分为ostream_iterator和istream_iterator,下面先通过一个简单的例子还介绍一下这两个迭代器的简单使用方法:(从istream_iterator读入数据通过copy复制到迭代器的代码请看 C++STL流迭代器 一文)

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
	copy(istream_iterator<int>(cin), istream_iterator<int>(), ostream_iterator<int>(cout, "\n"));
	return 0;
}

很简洁的一段代码,就是一个copy函数来实现。其实迭代器由一个标准输入迭代器来实现,终止迭代器是一个EOF标志,复制到输出迭代器。下面是istream_iterator的构造函数的介绍:

 

 

Function Description
istream_iterator() The default constructor: Constructs an end-of-stream iterator. This is a past-the-end iterator, and it is useful when constructing a "range".
istream_iterator(istream& s) Creates an istream_iterator that reads values from the input stream s. When s reaches end of stream, this iterator will compare equal to an end-of-stream iterator created using the default constructor.

这里在上面的代码中都用到了,ostream_iterator的构造函数介绍如下:

 

 

Function Description
ostream_iterator(ostream& s) Creates an ostream_iterator such that assignment of t through it is equivalent to s << t.
ostream_iterator(ostream& s, const char* delim) Creates an ostream_iterator such that assignment of t through it is equivalent to s << t << delim.

如果只有输出流参数,则输出之间没有间隔符,否则是一个const char*类型的间隔符(如果是string,记得通过string的c_str()成员函数转换一下)。

下面是两个其他的示例代码:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;

int main()
{
	ostream_iterator<int> intWriter(cout, "\n");
	
	*intWriter = 42;
	intWriter++;
	*intWriter = 77;
	intWriter++;
	*intWriter = -5;
	
	vector<int> coll;
	for(int i = 1; i <= 9; ++i)
	{
		coll.push_back(i);
	}
	
	copy(coll.begin(), coll.end(), ostream_iterator<int>(cout));
	cout << endl;
	
	copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " < "));
	cout << endl;
	
	return 0;
}

#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
	istream_iterator<int> intReader(cin);
	istream_iterator<int> intReaderEOF;
	
	while(intReader != intReaderEOF)
	{
		cout << "once: " << *intReader << endl;
		cout << "once again: " << *intReader << endl;
		++intReader;
	}
	
	return 0;
}

觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> STL stream iterator – 流迭代器
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.