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

前端 未结 3 876
忘了有多久
忘了有多久 2021-01-07 15:15

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

The map declaration looks like this.

map accounts;

ofstream os(o         


        
相关标签:
3条回答
  • 2021-01-07 15:54

    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.

    0 讨论(0)
  • 2021-01-07 16:08

    What you want to do is also known as Serialization

    Check this thread in another forum, it may help you

    0 讨论(0)
  • 2021-01-07 16:09

    You need to output them one by one.

    Binary writes do not work correctly on any class which (internally) contains a pointer. That certainly include std::map, std::string etc.

    0 讨论(0)
提交回复
热议问题