使用循环序列化和反序列化图形

时间:2014-12-05 13:46:32

标签: c++ serialization boost

我正在尝试使用Boost库序列化(保存)和反序列化(重新加载)一个对象,以便在创建多个对象后最大限度地减少开销内存需求。我是Boost库的新手,但到目前为止,我不想修改我正在使用的库。我尝试编写下面的代码但是我收到错误{错误C2039:'serialize':不是'DirectedGraphicalModels :: CGraph'E:\ external \ boost \ boost_1_54_0 \ boost \ serialization \ access.hpp 118}的成员。我正在使用的Graph库的标题是here

int main(int argc, char *argv[])
{
CImageGraph *pGraph     = new CGraph(nStates);  
cout << "Building the Graph..." << endl;
pGraph->buildImageGraphN4(fv.rows, fv.cols, pEdgeTrainer != NULL, true);

 // Save data
  {
    const char* fileName = "Graph.txt";
    // Create an output archive
    std::ofstream ofs(fileName);
    boost::archive::text_oarchive ar(ofs);
    // Save only the pointer. This will trigger serialization
    // of the object it points too, i.e., o1.
    ar & pGraph;
  }

  // Restore data
  CImageGraph *pRGraph     = new CGraph(nStates);   
  cout << "Building the Graph for restore..." << endl;
  pRGraph->buildImageGraphN4(fv.rows, fv.cols, pEdgeTrainer != NULL, true);
  pRGraph;
  {
     const char* fileName = "Graph.txt";
    // Create and input archive
    std::ifstream ifs(fileName);
    boost::archive::text_iarchive ar(ifs);
    // Load
    ar & pRGraph;
  }

  // Make sure we read exactly what we saved.
  assert(pRGraph != pRGraph);
  //assert(*pRGraph == pRGraph);

}

请告诉我如何继续保存并重新加载图表以便进一步处理。到目前为止,我已经提到了这些文章12,但我还没有清楚地理解这些概念。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要实现序列化功能。看到您不想修改库头,请添加如下的帮助程序:

#include <boost/serialization/vector.hpp>

namespace boost { namespace serialization {

      template <typename Ar>
      void serialize(Ar& ar, DirectGraphicalModels::CGraph& graph, const unsigned int version) {
           //// e.g.: 
           // ar & graph.title();
           // ar & graph.nodes(); // will use the default vector adaptation from the header above
           // ar & graph.edges(); // will use the default vector adaptation from the header above
      }

      template <typename Ar>
      void serialize(Ar& ar, DirectGraphicalModels::Node& node, const unsigned int version) {
           //// e.g.: 
           // ar & node.source;
           // ar & node.target;
      }

      // etc.

} }

默认情况下,对所有通过指针序列化的对象(de)进行对象跟踪。这样可以确保别名指针不会被(de)序列化两次,这意味着您可以(反)序列化循环图。