首页 > 解决方案 > 什么可用于在 c ++ 中保存图形等结构(Python pickle 等价物)

问题描述

我有一个带有边和顶点的图结构。我想像在 python 中酸洗一样序列化并保存它。我可以用来做什么?

标签: c++graphpickle

解决方案


C++ 本身不支持通用序列化。

因此,您有 3 个选项:

  1. 在 google 中搜索“c++ 序列化库”并使用它
  2. 自己写一堂课
  3. 使用 JSON 等标准

对于 2.:

通常,您在一个类中拥有图表的所有数据。您唯一需要做的就是覆盖类的插入器operator <<和提取器operator

我给你一个简单的例子:

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

std::istringstream testFile(R"(1 2 3
10 11 12)");

struct Graph
{
    int x,y;                  // Some example data
    int numberOfEdges;        // The number of elements in the vector
    std::vector<int> edges;   // An array of data

    // Serializing. Put the data into a character stream
    friend std::ostream& operator << (std::ostream& os, Graph& g) {
        os << g.x << ' ' << g.y << ' '<< g.numberOfEdges << '\n';
        std::copy(g.edges.begin(), g.edges.end(), std::ostream_iterator<int>(os, " "));
        return os;
    }

    // Deserializing. Get the data from a stream
    friend std::istream& operator >> (std::istream& is, Graph& g) {
        is >> g.x >> g.y >> g.numberOfEdges;
        std::copy_n(std::istream_iterator<int>(is), g.numberOfEdges, std::back_inserter(g.edges));
        return is;
    }
};

// Test program
int main(int argc, char *argv[])
{
    Graph graph{};

    // Read graph data from a file --> Deserializing
    testFile >> graph;
    // Put result to std::cout --> Serializing
    std::cout << graph;

    return 0;
}

推荐阅读