Output data to file using for_each C++?
I want to use the for_each function to out an object to file, it sounds crazy but is it possible?. I have tried myself but it开发者_Go百科 seems not to work. Here are what I have done so far:
//Sterling.h
template<class T>
void myfn(const T& t, const iostream& io = cout)
{
io << t;
}
template<class T>
class fefnptr{
public:
void operator()(const T& t, const iostream& io = cout) const
{
io << t;
}
};
class Sterling{
// also implement the operator<< and other functions in Sterling.cpp
};
//main.cpp
int main(){
fstream fp("test",fstream::out);
if(!fp) cerr << "Unable to open the file\n";
else
{
for_each(arr,arr+5,fefnptr<Sterling>(,fp)); // the syntax here is wrong and
I know that but I just want to put the fp as an parameter to output the object to the file
}
fp.close();
return 1;
}
And it turns out the error(of course I know what it is) missing parameter ( it is the object that I want to output to the file). So any idea for using for_each to output object to file? Thanks in advance!
Try something like:
for_each(arr,arr+5, bind2nd(fefnptr<Sterling>(), fp));
You should pass (a pointer or reference to) fp
to the constructor of fefnptr
and store it in that object. So write a suitable constructor, and you don't need this made-up (,fp)
thing, just fefnptr<Sterling>(&fp)
The advantage of passing a reference is that the code looks nicer. The advantage of passing a pointer is that you can't carelessly pass a temporary into the constructor of something that outlives it.
Also, you should use std::copy
and an ostream iterator for this, rather than for_each
, but you know your own mind best ;-)
It is possible, as the other answers indicate, but an (IMO) cleaner solution would be to use std::copy
and the stream iterators:
std::copy(arr, arr+5, std::ostream_iterator<Sterling>(fp));
精彩评论