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

How to save a object with vector or other standard library container to binary file in C++?

像这样的对象:

#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;
}

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

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));
}

顺便说一句,你应该避免 using namespace std;

正如评论中指出的(感谢@Daniel Langr),这仅适用于 ofstream 或其基础 类

operator<< 有效实现的类型

有些库可以帮助您存储到文件,但您也可以自己做。

如果你想要文件中的二进制格式的数据,那么你可以使用ostream::write()功能,并且为了保存一个容器,至少应该存储大小。

所以一个非常具体的函数是

void save(const A & a)
{
    std::ofstream out_file("path/to/output/file", std::ios::binary);
    size_t sz = a.i.size();
    out_file.write(reinterpret_cast<const char*>(&sz), sizeof(size_t));
    for (const auto& i: a.i) out_file.write(reinterpret_cast<const char*>(&i), sizeof(int));
}

最好将流传递给函数并让 class 保存函数调用容器保存函数,该函数依次保存每个条目,如下所示:

void save(std::ofstream& out, int i)
{
    out.write(reinterpret_cast<const char*>(&i), sizeof(int));
}

template<typename E> void save(std::ofstream& out, const std::vector<E>& v)
{
    size_t sz = v.size();
    out.write(reinterpret_cast<const char*>(&sz), sizeof(size_t));
    for (const auto& i: v) save(out, i);
}

void save(std::ofstream& out, const A & a)
{
    save(out, a.i);
}

这样,只要有保存功能,任何类型的条目的容器都可以保存。