通用算法笔记3

1,流迭代器.
ostream_iterator<int>(cout,"\n").//在最后的末端自动写入一个单独的字符串.
例1:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
using namespace std;

bool gt25(int x) { return 25 < 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"), gt25);
}

例2:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <fstream>
using namespace std;

bool gt25(int x) { return 25 < x; }

int main()
{
  int a[] = { 10, 20, 30 };
  const size_t SIZE = sizeof(a) / sizeof(a[0]);
  ofstream outf("out1.txt");
  remove_copy_if(a, a + SIZE, //*****输出到文件
                 ostream_iterator<int>(outf, "\n"), gt25);
}

例3:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;

#if 0
输入流迭代器:istream_iterator<>()
#endif

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

inline void assure(ifstream& in, const char* filename="")
{
    if(!in)
    {
        fprintf(stderr, "Could not open file %s\n", filename);
        exit(EXIT_FAILURE);
    }

}

int main()
{
  ofstream outf("someInts.dat");
  outf << "1 3 47 5 84 9";
  outf.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);
}

你可能感兴趣的:(算法)