C++ 输入输出流迭代器 笔记
来源:互联网 发布:18年网络教育改革 编辑:程序博客网 时间:2024/06/08 09:56
ostream_iterator 对象必须与特定的流绑定在一起。
ostream_iterator 不提供超出末端迭代器。
在创建ostream_iterator 对象时,可提供第二个(可选的)实参,指定将元素写入输出流时使用的分隔符。分隔符必须是 C 风格字符串。因为它是 C 风格字符串,所以必须以空字符结束;否则,其行为将是未定义的。
在创建 istream_iterator 时,可直接将它绑定到一个流上。另一种方法是在创建时不提供实参,则该迭代器指向超出末端位置。
考虑下面例子,可使用 istream_iterator 对象将标准输入读到 vector 对象中。
istream_iterator<int> in_iter(cin); // read ints from cin istream_iterator<int> eof; // istream "end" iterator // read until end of file, storing what was read in vec while (in_iter != eof) // increment advances the stream to the next value // dereference reads next value from the istream vec.push_back(*in_iter++);
重写程序:
istream_iterator<int> in_iter(cin); // read ints from cin istream_iterator<int> eof; // istream "end" iterator vector<int> vec(in_iter, eof); // construct vec from an iterator range
从标准输入读取一些数,再将读取的不重复的数写到标准输出:
istream_iterator<int> cin_it(cin); // reads ints from cin istream_iterator<int> end_of_stream; // end iterator value // initialize vec from the standard input: vector<int> vec(cin_it, end_of_stream); sort(vec.begin(), vec.end()); // writes ints to cout using " " as the delimiter ostream_iterator<int> output(cout, " "); // write only the unique elements in vec to the standard output unique_copy(vec.begin(), vec.end(), output);
从一个既支持 -- 也支持++ 的迭代器就可以定义反向迭代器,这不用感到吃惊。毕竟,反向迭代器的目的是移动迭代器反向遍历序列。标准容器上的迭代器既支持自增运算,也支持自减运算。但是,流迭代器却不然,由于不能反向遍历流,因此流迭代器不能创建反向迭代器。
图 11.2 阐明了这个问题:使用反向迭代器时,以逆序从后向前处理string 对象。为了得到正确的输出,必须将反向迭代器line.rbegin() 和 rcomma 转换为从前向后移动的普通迭代器。其实没必要转换line.rbegin(),因为我们知道转换的结果必定是line.end()。只需调用所有反向迭代器类型都提供的成员函数 base 转换rcomma 即可:
- C 笔记 输入输出
- C语言笔记---输入输出
- C学习笔记 文件输入输出
- C++(笔记)输入输出总结
- C++ 输入输出流迭代器 笔记
- C语言复习笔记二:输入输出
- C语言文件输入输出函数笔记
- 【C++】【学习笔记】【005】输入输出小结
- C输入输出
- C输入输出
- C 输入输出
- C输入输出
- C输入输出
- C-输入输出
- C输入输出
- C 输入输出
- C输入输出
- 【C++】输入输出
- hdu1040As Easy As A+B
- Kafka的Producer和Consumer的示例(使用java语言)
- g++ 编译 时常见错误
- Qt获取系统CPU信息
- Objective-C之@class,@protocol向前声明
- C++ 输入输出流迭代器 笔记
- TOJ 10007 The last non-zero digit of n!
- 黑龙江省2012年ACM-ICPC省赛J题The least average cost【最小均值回路】
- mysql常用总结
- C# .Net三层架构[转]
- 第八篇 Hibernate之9种查询方式
- 开发应用的时候第三方的库是不可缺少CocoaPods。
- Linkwedo 领度系统提升老板的效率
- vs2008命令窗口使用-命令