【转】istream_iterator, ostream_iterator,copy以及文件序列化

#include <iostream>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <numeric>
#include <string>
using namespace std;

int main()
{
 vector<int> vec_int;
 for (int i=0; i<10; i++)
  vec_int.push_back(i);
 partial_sum(vec_int.begin(), vec_int.end(), vec_int.begin());
 vector<double> vec_double;
 for (int i=0; i<10; i++)
  vec_double.push_back(2.11);
 partial_sum(vec_double.begin(), vec_double.end(), vec_double.begin());
 vector<string> vec_str;
 for (int i=0; i<10; i++)
  vec_str.push_back("hkx");
 partial_sum(vec_str.begin(), vec_str.end(), vec_str.begin());
 //
 ostream_iterator<int> out(cout, ";");
 copy(vec_int.begin(), vec_int.end(), out);
 ostream_iterator<double> out1(cout, ";");
 copy(vec_double.begin(), vec_double.end(), out1);
 ostream_iterator<string> out2(cout, ";");
 copy(vec_str.begin(), vec_str.end(), out2);
 //

 ofstream ofs;
 ofs.open("hkx.dat");
 assert(ofs!= 0);
 ostream_iterator<int> os(ofs, ";");
 copy(vec_int.begin(), vec_int.end(), os);
 ostream_iterator<double> os1(ofs, ";");
 copy(vec_double.begin(), vec_double.end(), os1);
 ostream_iterator<string> os2(ofs, ";");
 copy(vec_str.begin(), vec_str.end(), os2);
 ofs.close(); //必须close,否则下面的ofstream中读取不到数据
 //

 ifstream ifs;
 ifs.open("hkx.dat");
 assert(ifs != NULL);
 vec_int.clear();
 vec_double.clear();
 vec_str.clear();

 copy(istream_iterator<int>(ifs), istream_iterator<int>(), back_inserter(vec_int));
 int ttm = vec_int.size();
 copy(vec_int.begin(), vec_int.end(), ostream_iterator<int>(cout, " "));

 ifs.clear();
 ifs.ignore(10, ';');
 copy(istream_iterator<double>(ifs), istream_iterator<double>(), back_inserter(vec_double));
 copy(vec_double.begin(), vec_double.end(), ostream_iterator<double>(cout, " "));

 ifs.clear();
 ifs.ignore(10, ';');
 copy(istream_iterator<string>(ifs), istream_iterator<string>(), back_inserter(vec_str));
 copy(vec_str.begin(), vec_str.end(), ostream_iterator<string>(cout, " "));

 return 0;
}

转自:https://www.cnblogs.com/kex1n/archive/2011/01/17/2286432.html

posted @ 2020-06-04 17:26  天使冰王  阅读(145)  评论(0编辑  收藏  举报