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

前端 未结 3 875
忘了有多久
忘了有多久 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::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.

提交回复
热议问题