1、istream_iterator 对象上的操作

 
构造与流绑定在一起的 istream_iterator 对象时将对迭代器定位,以便第一次对该迭代器进行解引用时即可从流中读取第一个值。
 
考虑下面例子,可使用 istream_iterator 对象将标准输入读到 vector 对象中。
  1. istream_iterator in_iter(cin); // read ints from cin 
  2. istream_iterator eof; // istream "end" iterator 
  3. // read until end of file, storing what was read in vec 
  4. while (in_iter != eof) 
  5. // increment advances the stream to the next value 
  6. // dereference reads next value from the istream 
  7. vec.push_back(*in_iter++); 
这个循环从 cin 中读取 int 型数据,并将读入的内容保存在 vec 中。每次循环都检查 in_iter 是否为 eof。其中 eof 迭代器定义为空的 istream_iterator 对象,用作结束迭代器。绑在流上的迭代器在遇到文件结束或某个错误时,将等于结束迭代器的值。
 
本程序最难理解的部分是传递给 push_back 的实参,该实参使用解引用和后自增操作符。根据优先级规则(第 5.5 节),自增运算的结果将是解引用运算的操作数。对 istream_iterator 对象做自增运算使该迭代器在流中向前移动。然而,使用后自增运算的表达式,其结果是迭代器原来的值。自增的效果是使迭代器的流中移动到下一个值,但返回指向前一个值的迭代器。对该迭代器进行解引用获取该值。
 
更有趣的是可以这样重写程序:
  1. istream_iterator in_iter(cin); // read ints from cin 
  2. istream_iterator eof;      // istream "end" iterator 
  3. vector vec(in_iter, eof);  // construct vec from an iterator range 
这里,用一对标记元素范围的迭代器构造 vec 对象。这些迭代器是 istream_iterator 对象,这就意味着这段范围的元素是通过读取所关联的流来获得的。这个构造函数的效果是读 cin,直到到达文件结束或输入的不是 int 型数值为止。读取的元素将用于构造 vec 对象
 
1、ostream_iterator对象和使用
 
可使用 ostream_iterator 对象将一个值序列写入流中,其操作的过程与使用迭代器将一组值逐个赋给容器中的元素相同:
  1. // write one string per line to the standard output 
  2. ostream_iterator out_iter(cout, "\n"); 
  3. // read strings from standard input and the end iterator 
  4. istream_iterator in_iter(cin), eof; 
  5. // read until eof and write what was read to the standard output 
  6. while (in_iter != eof) 
  7. // write value of in_iter to standard output 
  8. // and then increment the iterator to get the next value from cin 
  9.    *out_iter++ = *in_iter++; 
这个程序读 cin,并将每个读入的值依次写到 cout 中不同的行中。
 
首先,定义一个 ostream_iterator 对象,用于将 string 类型的数据写到 cout 中,每个 string 对象后跟一个换行符。定义两个 istream_iterator 对象,用于从 cin 中读取 string 对象。while 循环类似前一个例子。但是这一次不是将读取的数据存储在 vector 对象中,而是将读取的数据赋给 out_iter,从而输出到 cout 上。
 
这个赋值类似于第 6.7 节将一个数组复制给另一个数组的程序。对这两个迭代器进行解引用,将右边的值赋给左边的元素,然后两个迭代器都自增 1。其效果就是:将读取的数据输出到 cout 上,然后两个迭代器都加 1,再从 cin 中读取下一个值。