本来不打算在这里写笔记的,因为我发现在豆瓣上做笔记很方便,而且对于一两句话的笔记来说更是非常的适合,不过我还是觉得豆瓣用的还不是很习惯,于是还是决定在这里记录一点读书笔记。
/**
** 使用istream_iterator读入一系列整数,
** 使用ostream_iterator分别将偶数写到一个文件中,使用换行符分隔每个数字,
** 将奇数写到另一个文件中,使用空格分隔每个数字。
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <iterator>
using std::istream_iterator;
using std::ostream_iterator;
using std::cin;
using std::cout;
using std::vector;
using std::ofstream;
bool is_even(int &n) {
return (n & 0x1) == 0x0;
}
int main() {
istream_iterator<int> in(cin), end_in;
vector<int> ivec(in, end_in);
ofstream odd_file("odd.txt"), even_file("even.txt");
ostream_iterator<int> odd_out(odd_file, " "), even_out(even_file, "\n");
for (vector<int>::iterator it(ivec.begin());
it != ivec.end(); ++it) {
if (is_even(*it)) {
*even_out++ = *it;
} else {
*odd_out++ = *it;
}
}
odd_file.close();
even_file.close();
return 0;
}
在程序中输入一下内容:
12 1233 3241 3413 13 34 4 23 1 321 31324 45 67 66 67 896 6734 9
odd.txt:
1233 3241 3413 13 23 1 321 45 67 67 9
even.txt:
12
34
4
31324
66
896
6734
这可比以前那种循环啊、调用函数啊什么的方便多了,不过流迭代器自身还是有一定的局限的,比如只能向前迭代,无法向后迭代。