流迭代器

本来不打算在这里写笔记的,因为我发现在豆瓣上做笔记很方便,而且对于一两句话的笔记来说更是非常的适合,不过我还是觉得豆瓣用的还不是很习惯,于是还是决定在这里记录一点读书笔记。

/**
** 使用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
这可比以前那种循环啊、调用函数啊什么的方便多了,不过流迭代器自身还是有一定的局限的,比如只能向前迭代,无法向后迭代。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值