我想使用 for_each 函数将一个对象输出到文件中,这听起来很疯狂,但是这可能吗?。我自己试过了,但似乎不起作用。以下是我到目前为止所做的:
//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;
}
结果是错误(我当然知道是什么)缺少参数(它是我要输出到文件的对象)。那么使用 for_each 将对象输出到文件有什么想法吗? 提前致谢!
最佳答案
尝试这样的事情:
for_each(arr,arr+5, bind2nd(fefnptr<Sterling>(), fp));
关于c++ - 使用 for_each C++ 将数据输出到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5989661/