C++编程思想 第2卷 第6章 通用算法 概述 流迭代器

像任何好的软件库一样
标准C++库试图提供便捷的方法以自动完成常见的任务
可以使用通用算法来取代循环结构一个流迭代器使用流作为输入或输出序列

//: C06:CopyInts3.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Uses an output stream iterator.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
using namespace std;

bool gt15(int x) { return 15 < x; }

int main() {
  int a[] = { 10, 20, 30 };
  const size_t SIZE = sizeof a / sizeof a[0];
  remove_copy_if(a, a + SIZE,
                 ostream_iterator<int>(cout, "\n"), gt15);
  getchar();
} ///:~

输出
10
remove_copy_if()的第3个参数位置上的输出序列b用一个输出流迭代器来替代
这个迭代器是在头文件<iterator>中声明的ostream_iterator类模板的一个实例
用一个输出文件流来代替cout,使得写文件同样容易实现

//: C06:CopyIntsToFile.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Uses an output file stream iterator.
#include <algorithm>
#include <cstddef>
#include <fstream>
#include <iterator>
using namespace std;

bool gt15(int x) { return 15 < x; }

int main() {
  int a[] = { 10, 20, 30 };
  const size_t SIZE = sizeof a / sizeof a[0];
  ofstream outf("ints.out");
  remove_copy_if(a, a + SIZE,
                 ostream_iterator<int>(outf, "\n"), gt15);
} ///:~

输出 ints.out
10
一个输入流迭代器允许算法从输入流中获得它的输入序列
靠构造函数和operator++()的基础的流中读入下一个元素
算法需要两个指针来限定输入序列
可以用两种方式来构造istream_iterator

//: C06:CopyIntsFromFile.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Uses an input stream iterator.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include "../require.h"
using namespace std;

bool gt15(int x) { return 15 < x; }

int main() {
  ofstream ints("someInts.dat");
  ints << "1 3 47 5 84 9";
  ints.close();
  ifstream inf("someInts.dat");
  assure(inf, "someInts.dat");
  remove_copy_if(istream_iterator<int>(inf),
                 istream_iterator<int>(),
                 ostream_iterator<int>(cout, "\n"), gt15);
  getchar();
} ///:~

输出
1
3
5
9

程序中replace_copy_if()的第1个参数
把一个istream_iterator的对象应用于含有整数的输入文件流
第2个参数使用istream_iterator类的默认构造函数

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82219942