如何将带有矢量或其他标准库容器的对象保存到C ++中的二进制文件?

nul*_*ptr 0 c++ binary fstream stream c++11

像这样的对象:

#include <vector>
using namespace std;
class A
{
public:
    vector<int> i;
    //save other variable
};

void save(const A & a)
{
    //dosomething
}

int main()
{
    A a;
    save(a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何将其保存到二进制文件?换句话说,如何编写保存功能?

bar*_*top 5

ofstreamcopy应满足:

void save(const A & a)
{
    std::ofstream out_file("path/to/output/file", std::ios::binary);
    std::copy(a.i.begin(), a.i.end(), std::ostream_iterator<int>(out_file));
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您可能应该避免using namespace std;

正如注释中指出的(感谢@Daniel Langr),这仅适用于具有operator<<for ofstream或其基类的有效实现的类型