dor_amit@hotmail.com Guest
|
Posted: Thu May 25, 2006 2:21 pm Post subject: Implementing writing of a matrix to 2 destinations |
|
|
Hi,
I am trying to implement serialization of a matrix to stdout and to a
file. Requirements are:
a) Each serialization uses 2 delimiters: a column delimiter and a row
delimiter.
b) The pair of delimiters for file serialization differs from that of
stdout serialization.
I've tried this:
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <stdlib.h>
using namespace std;
typedef vector<int> IntVec;
typedef vector<IntVec> IntMat;
namespace std
{
ostream& operator<<(ostream& o,const IntVec& v)
{
copy(v.begin(),v.end(),ostream_iterator<IntVec::value_type>(o,"
"));
}
ostream& operator<<(ostream& o,const IntMat& m)
{
copy(m.begin(),m.end(),ostream_iterator<IntMat::value_type>(o,"\n"));
}
ofstream& operator<<(ofstream& o,const IntVec& v)
{
copy(v.begin(),v.end(),ostream_iterator<IntVec::value_type>(o,"|"));
}
ofstream& operator<<(ofstream& o,const IntMat& m)
{
// problem: ostream_iterator is instatiated, leading to this
calling
// the serialization to STDOUT
copy(m.begin(),m.end(),ostream_iterator<IntMat::value_type>(o,"$$$\n"));
}
};
int main()
{
ofstream file("my_out.txt");
IntVec v0,v1,v2;
generate_n(back_inserter(v0),5,rand);
generate_n(back_inserter(v1),5,rand);
generate_n(back_inserter(v2),5,rand);
IntMat m;
m.push_back(v0);
m.push_back(v1);
m.push_back(v2);
cout << m;
return 0;
}
Serialization to STDOUT works fine. However, as far as
file-serialization goes, this brings me only half-way, since
operator<<(ofstream& o,const IntMat& m) resolves to calling ostream&
operator<<(ostream& o,const IntVec& v) (READ: the serialization of a
row to file calls serialization of column to stdout).
Any ideas?
Amit
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|