草庐IT

c++ - 将对象保存到二进制文件中的有效方法

coder 2024-02-20 原文

我有一个基本上由 vector 矩阵组成的类:vector< MyFeatVector<T> > m_vCells ,其中外部 vector 表示矩阵。这个矩阵中的每个元素都是一个 vector (我扩展了 stl vector 类并将其命名为 MyFeatVector<T> )。

我正在尝试编写一种有效的方法来将此类的对象存储在二进制文件中。 到目前为止,我需要三个嵌套循环:

foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );

哪里this->at(dy,dx,dz)检索 dz位置 [dy,dx] 处的 vector 元素.

是否有可能存储 m_vCells不使用循环的私有(private)成员?我试过类似的东西:foutput.write(reinterpret_cast<char*>(&(this->m_vCells[0])), (this->m_vCells.size())*sizeof(CFeatureVector<T>));这似乎无法正常工作。我们可以假设这个矩阵中的所有 vector 都具有相同的大小,尽管也欢迎更通用的解决方案:-)

此外,按照我的嵌套循环实现,将此类对象存储在二进制文件中似乎比将相同对象存储在纯文本文件中需要更多的物理空间。这有点奇怪。

我试图遵循 http://forum.allaboutcircuits.com/showthread.php?t=16465 下的建议但无法得出合适的解决方案。

谢谢!

下面是我的 serialization 的简化示例和 unserialization方法。

template < typename T >
bool MyFeatMatrix<T>::writeBinary( const string & ofile ){

    ofstream foutput(ofile.c_str(), ios::out|ios::binary);
    foutput.write(reinterpret_cast<char*>(&this->m_nHeight), sizeof(int));
    foutput.write(reinterpret_cast<char*>(&this->m_nWidth), sizeof(int));
    foutput.write(reinterpret_cast<char*>(&this->m_nDepth), sizeof(int));

    //foutput.write(reinterpret_cast<char*>(&(this->m_vCells[0])), nSze*sizeof(CFeatureVector<T>));
    for(register int dy=0; dy < this->m_nHeight; dy++){
       for(register int dx=0; dx < this->m_nWidth; dx++){
          for(register int dz=0; dz < this->m_nDepth; dz++){
              foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
          }
       }
    }

    foutput.close();
    return true;
}

template < typename T >
bool MyFeatMatrix<T>::readBinary( const string & ifile ){

    ifstream finput(ifile.c_str(), ios::in|ios::binary);

    int nHeight, nWidth, nDepth;
    finput.read(reinterpret_cast<char*>(&nHeight), sizeof(int));
    finput.read(reinterpret_cast<char*>(&nWidth), sizeof(int));
    finput.read(reinterpret_cast<char*>(&nDepth), sizeof(int));

    this->resize(nHeight, nWidth, nDepth);

    for(register int dy=0; dy < this->m_nHeight; dy++){
        for(register int dx=0; dx < this->m_nWidth; dx++){
            for(register int dz=0; dz < this->m_nDepth; dz++){
                finput.read( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
            }
        }
    }
    finput.close();
    return true;
}

最佳答案

最有效的方法是将对象存储到数组(或连续空间)中,然后将缓冲区爆破到文件中。一个优点是磁盘盘片不会浪费时间增加,而且写入可以连续执行,而不是在随机位置执行。

如果这是你的性能瓶颈,你可能要考虑使用多线程,一个额外的线程来处理输出。将对象转储到缓冲区中,设置标志,然后写入线程将处理输出,将您的主要任务留给执行更重要的任务。

编辑 1:序列化示例
以下代码未经编译,仅供说明之用。

#include <fstream>
#include <algorithm>

using std::ofstream;
using std::fill;

class binary_stream_interface
{
    virtual void    load_from_buffer(const unsigned char *& buf_ptr) = 0;
    virtual size_t  size_on_stream(void) const = 0;
    virtual void    store_to_buffer(unsigned char *& buf_ptr) const = 0;
};

struct Pet
    : public binary_stream_interface,
    max_name_length(32)
{
    std::string     name;
    unsigned int    age;
    const unsigned int  max_name_length;

    void    load_from_buffer(const unsigned char *& buf_ptr)
        {
            age = *((unsigned int *) buf_ptr);
            buf_ptr += sizeof(unsigned int);
            name = std::string((char *) buf_ptr);
            buf_ptr += max_name_length;
            return;
        }
    size_t  size_on_stream(void) const
    {
        return sizeof(unsigned int) + max_name_length;
    }
    void    store_to_buffer(unsigned char *& buf_ptr) const
    {
        *((unsigned int *) buf_ptr) = age;
        buf_ptr += sizeof(unsigned int);
        std::fill(buf_ptr, 0, max_name_length);
        strncpy((char *) buf_ptr, name.c_str(), max_name_length);
        buf_ptr += max_name_length;
        return;
    }
};


int main(void)
{
    Pet dog;
    dog.name = "Fido";
    dog.age = 5;
    ofstream    data_file("pet_data.bin", std::ios::binary);

    // Determine size of buffer
    size_t  buffer_size = dog.size_on_stream();

    // Allocate the buffer
    unsigned char * buffer = new unsigned char [buffer_size];
    unsigned char * buf_ptr = buffer;

    // Write / store the object into the buffer.
    dog.store_to_buffer(buf_ptr);

    // Write the buffer to the file / stream.
    data_file.write((char *) buffer, buffer_size);

    data_file.close();
    delete [] buffer;
    return 0;
}

编辑 2:具有字符串 vector 的类

class Many_Strings
    : public binary_stream_interface
{
    enum {MAX_STRING_SIZE = 32};

    size_t    size_on_stream(void) const
    {
        return m_string_container.size() * MAX_STRING_SIZE  // Total size of strings.
               + sizeof(size_t); // with room for the quantity variable.
    }

    void      store_to_buffer(unsigned char *& buf_ptr) const
    {
        // Treat the vector<string> as a variable length field.
        // Store the quantity of strings into the buffer,
        //     followed by the content.
        size_t string_quantity = m_string_container.size();
        *((size_t *) buf_ptr) = string_quantity;
        buf_ptr += sizeof(size_t);

        for (size_t i = 0; i < string_quantity; ++i)
        {
            // Each string is a fixed length field.
            // Pad with '\0' first, then copy the data.
            std::fill((char *)buf_ptr, 0, MAX_STRING_SIZE);
            strncpy(buf_ptr, m_string_container[i].c_str(), MAX_STRING_SIZE);
            buf_ptr += MAX_STRING_SIZE;
        }
    }
    void load_from_buffer(const unsigned char *& buf_ptr)
    {
        // The actual coding is left as an exercise for the reader.
        // Psuedo code:
        //     Clear / empty the string container.
        //     load the quantity variable.
        //     increment the buffer variable by the size of the quantity variable.
        //     for each new string (up to the quantity just read)
        //        load a temporary string from the buffer via buffer pointer.
        //        push the temporary string into the vector
        //        increment the buffer pointer by the MAX_STRING_SIZE.
        //      end-for
     }
     std::vector<std::string> m_string_container;
};

关于c++ - 将对象保存到二进制文件中的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6549731/

有关c++ - 将对象保存到二进制文件中的有效方法的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  6. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  7. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  8. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  9. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  10. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

随机推荐