c++ - 使用 for_each C++ 将数据输出到文件?

标签 c++

我想使用 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/

相关文章:

c++ - 从文件中读取数字,递增并写回

c++ - 损坏的堆可以清理吗?

c++ - Makefile,源码在多个目录,依赖问题

c++ - 如果在循环条件中使用 strlen 会被计算多次吗?

c++ - 如何在 C++ 中拆分长行代码?

c++ - 构建失败错误 : Cannot build C++ SDK Helloworld with qibuild

c++ - 为什么类型推导不能按预期工作?

c++ - std::atomic<T>::notify_all 是如何排序的?

c++ - 了解 SFINAE

C++ 继承和指针错误(初学者)