如何输出一个std ::地图为二进制文件? [英] How to output a std::map to a binary file?

查看:163
本文介绍了如何输出一个std ::地图为二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能输出的std ::地图来的二进制文件?

How can I output a std::map to a binary file?

该地图声明看起来是这样的。

The map declaration looks like this.

map<string, Account *> accounts;

ofstream os(outFileName.c_str());
os.write(  );

我需要知道什么装进的write()函数有它的工作就是我想要的。我需要输出的类别帐户一个接一个或我是安全的,只是它输出为地图

I need to know what to put into the write() function to have it work the way I want. Do I need to output the class Account one-by-one or am I safe to just output it as a map?

推荐答案

既然你把它作为指针,你将不得不遍历在地图上,首先存储密钥,然后指向的帐户,一个之一。

Since you're storing it as pointers, you will have to iterate over the map, storing first the key, and then the pointed-to Account, one by one.

这似乎喜欢的事,可以做一个更好的数据库。特别是如果你将需要为此在多个地方。

This seems like something that could be done better with a database. Especially if you're going to need to do this in more than one place.

使用对象这样的做法被称为序列化。

The practice of doing this with objects is known as serialization.

如果您的账户类是什么作为一个普通的旧数据类(即它不包含任何指针,也没有有别于其他普通的旧数据类和结构类或结构),你可以简单地直接写入内存到一个文件中。在这种情况下,像下面的方法是可以接受的:

If your Account class is what's known as a plain old data class (i.e. it contains no pointers and no classes or structs apart from other plain old data classes and structs) you can simply write its memory directly to a file. In that case, an approach like the following would be acceptable:

int32_t sizeAccount = sizeof(Account); // this should always be a 32 bit int
for (map<string, Account *>::iterator i = accounts.begin(); i != accounts.end(); ++i)
{
    int32_t sizeStr = i->first.length() + 1; // this should always be a 32 bit int

    os.write(&sizeStr, sizeof(sizeStr)); // 4 byte length of string
    os.write(i->first.c_str(), sizeStr); // null terminated string

    os.write(&sizeAccount, sizeof(sizeAccount)); // 4 byte size of object
    os.write(i->second, sizeAccount);    // object data itself
}

如果,然而,你的对象具有任何指针构件,或具有指针构件的类型的任何成员,或任何亚类或超类,或具有亚类或超类等种类的任何成员,这种方法可能是不够并且可能会产生两种无意义或纯不正确的输出。

If, however, your object has any pointer members, or any members of a type that have pointer members, or any subclasses or superclasses, or any members of types that have subclasses or superclasses, etc, this approach may not be sufficient and may yield either nonsensical or plain incorrect output.

这篇关于如何输出一个std ::地图为二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆